Array Behaviour in Javascript Array Behaviour in Javascript arrays arrays

Array Behaviour in Javascript


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


Arrays are objects in JavaScript. Hence, arr[0] assignment after console.log assigning the array on the same reference where first var arr = [[2,2]]; refer. Both arr variables refer to the same single object.

It happens only with objects but not with Primitive values like numbers.

Example with primitive value

var arr = 1;console.log('Array is',arr); // 1arr++;console.log('Array is',arr); // 2

Example with objects :

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

To avoid that you can use this :

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