Back to the Basics: Pass by Value vs Pass by Reference

Last Modified
Last updated December 1, 2022
When you assign variables to primitive types, they exist in memory. a = 5, b = 5 - these are pass by value. Objects on the other hand are pass by reference
 

Pass by Value:

Copy the value and create the value somewhere else in memory
var a = 5; var b = 10; // both have an address where the primitive value sits in memory var b = a; b++; console.log(a) // 5 console.log(b) // 6 // because of pass by value. b copies the primitive type value 5

Pass by Reference:

let obj1 = { name: 'John', password: '123' }; let obj2 = obj1; obj2.password = 'easypeasy'; console.log(obj1); // { name: 'John', password: 'easypeasy' } console.log(obj2); // { name: 'John', password: 'easypeasy' } // Because of pass by reference // Objects are stored in memory and passed by reference, not copied. // obj2 = obj1 -> points to the same place in memory var c = [1,2,3,4,5]; var d = c; d.push['50000'] console.log(d); // [1,2,3,4,5, 50000] console.log(c); // [1,2,3,4,5, 50000] // What if I want to clone/copy an object? // Array var e = [].concat(c); // [1,2,3,4,5] // Object let obj3 = {a: 'a', b: 'b', c: 'c'}; // What if I want to have it in another location in memory? // NOT obj4 = obj3 // Shallow clone with Object.assign let objClone = Object.assign({}, obj3); obj3.c = 5; // Doesn't change, because we cloned it console.log(objClone); // {a: 'a', b: 'b', c: 'c'}; // ES6 feature for shallow cloning let clone2 = {...obj3}; let obj4 = {a: 'a', b: 'b', c: { deep: 'try and copy me' }}; // Cloning doesn't work beyond the first level (with the previous methods) // The object in c is pass by reference, even though the first-level object was cloned to a new address in memory // How do we deep clone? let superClone = JSON.parse(JSON.stringify(obj4)); // This is not an exhaustive tool for cloning everything. // There are better ways of deep cloning
Why is this good?
  • Saving space in memory, referencing one location
Why is this bad?
  • Accidental changes to referenced objects