Javascript: Pass By Reference Or By Value?
Is Javascript pass by reference or pass by value? In fact, it’s a little bit of
both. Primitives: null, undefined, Number, String, & Boolean are pass by value,
and Objects: Array, Function, & Objects are pass by reference.
Unsure what we mean? Let’s check some examples with comments to see exactly!
// Primitives won't get changed, because we copy (pass) the value
// so the underlying value won't get changed
let a = 1 ;
let b = a ;
a = 5 ;
console . log ( a ); // 5
console . log ( b ); // 1
// we copy by reference meaning when we assign b to a we copy the location in memory
// meaning the underlying object will get changed
let a = {};
let b = a ;
a . foo = 'bar' ;
console . log ( a ); // {foo: "bar"}
console . log ( b ); // {foo: "bar"}
// same is true for arrays, the underlying array will get changed
let z = [];
let x = z ;
z . push ( 'apple' );
console . log ( z ); // ["apple"]
console . log ( x ); // ["apple"]
Javascript functions also behave similarly:
// functions can change the object without even returning the object because
// it is changing the same referenced object
function changeGrade ( student ) {
student . math = 'A' ;
}
let student = {
math : 'F' ,
history : 'B'
};
changeGrade ( student );
console . log ( student ); // {math: "A", history: "B"}
// A boolean is a primitive so it is passed by value so will not get
// changed when passed to a function
function primitiveUnchanged ( didPass ) {
didPass = true ;
}
let didPass = false ;
primitiveUnchanged ( didPass );
console . log ( didPass ); // false
A couple of good overviews can be found on:
Instagram Post