Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Behaviour in Javascript

I tried executing the code in Chrome Developer Console and i got this odd result which am not able to understand

var arr = [[2,2]];console.log('Array is',arr);arr[0] = [3,3]

The output i got after executing this is

Array is [[3,3]]

The assignment should happen after the console.log had been executed.But it magically happened before that.

To clarify i tried running the same code in JsBin.However in JSBin i got the expected out which is

Array is [[2,2]]

However this code yields expected result in chrome

var arr = [2,2];console.log('Array is',arr);arr[0] = 3;console.log(arr)

Output Array is [2,2] [3,2]

Can someone help me understand this.

like image 947
Sunil Hari Avatar asked Apr 10 '18 05:04

Sunil Hari


People also ask

What is the difference between [] and {} in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.

What do [] mean in JavaScript?

It is shorthand for empty array. Same as new Array(). Also {} is an empty object. Objects are like hashtables in Js so you can use it as a dictionary. Copy link CC BY-SA 2.5.

How does array work in JavaScript?

JavaScript arrays are zero-indexed: the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 . JavaScript array-copy operations create shallow copies.


1 Answers

This is because chrome puts the value of the variable assignment in the console, when you initialize / declare a variable. This is an expected behavior.

enter image description here

like image 61
Sreekanth Avatar answered Oct 07 '22 12:10

Sreekanth