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)?