Thursday, January 7, 2016

Javascript confusions and tricks

1. Console.log output of an array of objects VS an array of primitive value
Console.log output of objects is a pointer, not real value.
For example:
var array = [1,2,3,4,5,6,7,8,9];
console.log("start");
for(var i = 0; i < array.length; i++){
  console.log(i + " = " + array[i]);
  console.log(array);
}
console.log(array);
console.log("end");
array.push(9999);

The result out put is:
start
0 = 1
[1, 2, 3, 4]
1 = 2
[1, 2, 3, 4]
2 = 3
[1, 2, 3, 4]
3 = 4
[1, 2, 3, 4]
[1, 2, 3, 4]
end

But the output of this:

var array = [{value:1},{value:2},{value:3},{value:4}];
console.log("start");
for(var i = 0; i < array.length; i++){
  console.log(i + " = " + array[i]);
  console.log(array);
}
console.log(array);
console.log("end");
array.push({value:9999});
is:
start
0 = [object Object]
[Object, Object, Object, Object]
  ->0: Object1:
  ->1: Object2:
  ->2: Object3:
  ->3: Object4:
  ->4: Object
        value: 9999
         ->__proto__: Object
         length: 5
         ->__proto__: Array[0]
1 = [object Object]
[Object, Object, Object, Object]
2 = [object Object]
[Object, Object, Object, Object]
3 = [object Object]
[Object, Object, Object, Object]
[Object, Object, Object, Object]
end