Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why javascript "for loop" has different behaviours for different type of objects

I realise JavaScript has no pointers, however I noticed this "pointer" behaviour when looping through arrays that contains objects, but not the similar behaviour when an array contains numbers (for instance).

var ARR_num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (var i = 0, len = ARR_num.length; i < len; i++) {
  var item = ARR_num[i];
  item++;
}
console.log(ARR_num);
//Outputs [0,1,2,3,4,5,6,7,8,9]

Now with an array with objects

var ARR_obj = [{}, {}, {}];
for (var i = 0, len = ARR_obj.length; i < len; i++) {
  var item = ARR_obj[i];
  item.pointer = true;
}
console.log(ARR_obj);
//Outputs [{pointer: true}, {pointer: true}, {pointer: true}]

Why these two distinct behaviours?

like image 376
Hefler Avatar asked Nov 07 '22 17:11

Hefler


1 Answers

Why these two distinct behaviors?

when you assign an object to another variable, the new variable points to same objects hence when you change new variables properties, the Objects gets mutated example:

var a= {name: "some"};
var b = a;
b.name = "newName";
console.log(a.name);// "newName"

when you assign a primitive type to another variable, its just a new variable and has no reference to old variable, hence changing new variable won't affect old one. example:

var a = "some";
var b = a;
b = "newName";
console.log(a);//"some"

hope this will help!!

like image 89
Nemani Avatar answered Nov 14 '22 21:11

Nemani