Saturday, October 15, 2016

JavaScript Object References

Recently people asked me how JavaScript keep references while passing through function parameters including angular promise, underscore and normal JS code. I will provide one example from each section to show how references are passed.

Under Score (Lodash) Example

Some of the Underscore library functions return object reference while other returns new object. e.g. _.find method returns reference of the object that was found. in the following example when we change the value of variable "f.a", it affects "chkUnder" variable. While in case of _.where method, if we change the value of "w.a", it never changes the variable "chkUnder".

var chkUnder = [{ a: 1 }, { a: 2 }, { a: 3 }];
var f = _.find(chkUnder, { a: 2 });
f.a = 22;
var w = _.where(chkUnder, { a: 2 });
w.a = 24;