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?
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!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With