Why can objects that are passed into a function be mutated but not reassigned in javascript?

Viewed 814

I'm a beginner with Javascript and just need some clarification. I'm not really trying to achieve anything in particular here. Just a bit confused about this scenario.

When a variable assigned to an object is passed into a function as an argument, we can mutate the object permanently. However, we can't reassign it and make the changes stick. Why is that?

Here is some example code to what I mean:

Example1 - Mutation.

const house = {
  color1: 'white',
  color2: 'blue'
};

let paintIt = obj => {
  obj.color1 = 'gold'
};

paintIt(house);

house.color1 // Returns 'gold'

Example2 - Reassignment.

let house = {
  color1: 'white',
  color2: 'blue'
};

let paintItReassignment = obj => {
  obj = {
    forSale : false,
    includesGarden : true
  }
  console.log(obj) // Prints {'forSale':false, 'includesGarden':true}
};

paintItReassigment(house) // The reassignment does not work
house // Still returns {color1:'white', color2:'blue'}

house = {
 forSale : false,
 includesGarden : true
}; // Regular reassignment still works

Why does it stick when you modify the objects property (example1) but not when you reassign it (example2)?

1 Answers

Unlike some other programming languages such as C, JavaScript uses a mixture of pass-by-reference and pass-by-value systems for its function calls. In a function, you can reassign the properties of an object passed to it, but you can't reassign the variable of the object itself. You can always do the following if you wish to reassign an object variable:

o = f(o);

To redefine multiple variables:

var {a,b} = f(a,b)

where, for instance:

function f(a,b){
    return {a:b,b:a};
}

Some discussion about this topic can be found here.

Related