Understand JavaScript’s value passing and reference passing and pull out deep and shallow copies

Before we begin, let’s look at data types: primitive (also known as primitive data types) and reference types

  • Primitive type (undefined, Null, Boolean, Number, String)
  • Reference types (Array, Function, Object)

So, what’s the difference between a primitive type and a reference type?

Primitive types are assigned by value. A variable is assigned to another variable, in effect making a copy of the corresponding value, and then assigning the value to the new variable. We call this value passing

Reference type assignments are passed by reference. When a variable is assigned to another reference type, it records only one memory address where the specific data is stored. Note that variables pointing to primitive data types contain data, whereas variables pointing to non-primitive data types do not themselves contain data.


// Value type let a = 1 let b = a a = 5 console.log(b) // 1Copy the code

Completely independent copies, non-interference, we change the value of A, b is not affected.

Function change(person) {person. Age = 25 return person} let alex = {age: 30}; let changedAlex = change(alex) console.log(alex) // { age: 25 } console.log(changedAlex) // { age: 25 }Copy the code

Objects are passed by reference, not by value. That is, the variable assignment just passes the address, alex and changedAlex pointing to the same array. If we update alex, the changedAlex will also be affected.

variable address object
alex # 001 age: 30
changedAlex # 001
* * *

Reference reassignment

If we reassign an already assigned object, it will contain the new data or reference address.

var obj = { a: '111' }
obj = { b: '222' }
console.log(obj) // { b: '222' }
Copy the code

Obj changes from pointing to the first object to pointing to the second object

variable address object
obj # 001 a: ‘111’
# 002 b: ‘222’

If an object is not pointed to by any variable, like the first object (address #001), the JavaScript engine’s garbage collection mechanism destroys the object and frees memory.


In the reference type code above, Alex and changedAlex point to the same array. So how do we keep him from changing? This uses deep copy

function change(person) {
    var newPersonObj = JSON.parse(JSON.stringify(person));
    newPersonObj.age = 25;
    return newPersonObj;
}
var alex = {
    name: 'Alex',
    age: 30
};
var alexChanged = change(alex);
console.log(alex); // { name: 'Alex', age: 30 }
console.log(alexChanged); // { name: 'Alex', age: 25 }
Copy the code

Practice is the mother of wisdom

function changeAgeAndReference(person) { person.age = 25; person = { name: 'John', age: 50 }; return person; } var personObj1 = { name: 'Alex', age: 30 }; var personObj2 = changeAgeAndReference(personObj1); console.log(personObj1); // -> output? console.log(personObj2); // -> output?Copy the code

The answer is in the comments