3 ms·
EDIT: I am wrong. Below quote is irrelevant. I misunderstood the term "pass by reference", and confused it with mutable entities. It is for objects, not primit
by aeharding 9y ago
EDIT: I am wrong. Below quote is irrelevant. I misunderstood the term "pass by reference", and confused it with mutable entities.
It is for objects, not primitives.
> JavaScript has 6 primitive data types: string, number, boolean, null, undefined, symbol (new in ES6). With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable.
https://stackoverflow.com/a/13266769/1319878 https://stackoverflow.com/a/13266769/1319878
- amarshall 9y agoThe object is still passed by value, however the object itself contains references, which may be mutated. If objects were pass by reference then you’d end up with {a: 2} at the end: let a = {a: 1} function foo(a) { a = {a: 2} } foo(a) a //=> {a: 1} Don’t confuse passing a mutable entity by value with pass by reference.
- mnarayan01 9y ago> The object is still passed by value, however the object itself contains references, which may be mutated. This would imply that: var v = 1; (function (o) { o.a = 2; }({ a: v }); console.log(v); // => 2 The whole "objects are pass-reference-by-value" is obviously annoying and confusing, but we're kind of stuck with it.
- shkkmo 9y agoApparently there is another term (which I hadn't heard) which is: call-by-sharing https://en.m.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing https://en.m.wikipedia.org/wiki/Evaluation_strategy#Call_by_...
- kevincennis 9y agoThat's irrelevant. Look, same example but with an object. let a = { bar: 'baz' }; function foo( a ) { a = { beep: 'boop' }; } foo( a ); console.log( a ); // { bar: 'baz' }
- n0us 9y agoAnother way to think about it is that you just get a new reference to the same object, inside foo you are changing what 'a' refers to instead of what 'b' refers to. Using 'let' to declare 'b' is not necessary and using 'const' works just as well. $ node > const b = { bar: 'baz' } > function foo(a){ a = {beep: 'boop'}; } > foo(b) > console.log(b) { bar: 'baz' } >
- lowkeyokay 9y agoI thought this was just a matter of scope. a declared outside of the function is not the same as the one declared as a parameter.
- LoSboccacc 9y agothat answer doesn't concern with the pass-by semantic, only with the primitive/object semantics. this is the gist of the issue, fetched from http://javadude.com/articles/passbyvalue.htm http://javadude.com/articles/passbyvalue.htm about java but exemplifies perfectly the pass by reference semantics: "If you can write such a method/function in your language such that calling Type var1 = ...; Type var2 = ...; swap(var1,var2); actually switches the values of the variables var1 and var2, the language supports pass-by-reference semantics." as java javascript is reference-by-value