javascript is pass by value
javascript primitive varialbles are passed by value to a function. Objects are also passed by value but the difference is that the value of the reference of the object is passed to a function. The snippet below, the value of the references of b and c are passed into the function. Within the function, the change to the b is changing the internal value of the object, thus the change will be visible to all other references that is pointing to this object. The changes to the c is changing the value of reference itself by creating a brand new object, so the value of the reference is pointing to a new object, the old object stays the same.
function doUpdate(a, b, c) { a = a * 2; b.msg = "hey"; c = {msg: "hey"}; } var num = 10; var obj1 = {msg: "greetings"}; var obj2 = {msg: "greetings"}; doUpdate(num, obj1, obj2); console.log(num); // 10 console.log(obj1.msg); // hey console.log(obj2.msg); // greetings
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts