4 ms·
If you make a change to an integer that was in a variable and passed in by parameter, does Javascript really make the change to the caller's variable?
by cma 14y ago
If you make a change to an integer that was in a variable and passed in by parameter, does Javascript really make the change to the caller's variable?
- cynwoody 14y agoNo. However, if you pass an object or an array, the called function can change a field in the object or an element in the array (the difference between those two is an optimization), and the change will be visible to the caller. Go, however, lets you pass in an explicit pointer to an int, through which the function can change the int to which the caller pointed. Of ourse, the caller can also change the passed-in pointer if it wants, but that has no effect on the caller's variable.
- the_gipsy 14y agoJavascript primitives (number, string, boolean) are always copied, the remaining (object, function) are passed by reference (arrays are objects). Similar to Java.
- eonwe 14y agoNo. The scenario you posit would be true if JavaScript were call-by-reference. JavaScript, however, is call-by-value. Primitive types (string, number, boolean) are passed to functions by copying their value, and reference types (such as any object you create) are passed by copying the value of their reference. The reference semantics can be observed in JavaScript in some cases, such as: var i = 0; for (i = 0; i < 10; i++) { setTimeout(function() { document.write("i is now " + i); }, 10); } Here the inner function gets reference of the variable i instead of its value.