+ 2
Explain the Output
var likes=100; var person={ name:"jhon", class:5 } function myFun(a,b){ a=200; b.name="jhonny"; } myFun(likes, person); console.log(likes); console.log(name.person); Can anyone explain the output why output is: 100 and jhonny.instead of 200 and jhonny.
1 Answer
+ 4
The 'likes' variable is passed to the myFunc() function where its value is copied to the local variable 'a'. Inside the function, the local copy of the variable 'a' has its value changed to 200. The value of 'likes' isn't changed only its the copy's value is changed as they are 2 different variables.
However, when the 'person' object is passed, its reference to its location in memory's value is what is actually passed into the myFunc() function and that reference value is what is copied to the 'b' variable. So when the 'b' variable is used with dot notation (b.name) it is referring back to the original objects location in memory. Therefore, the object's property values are changed directly.