0

I'm confused on what is the difference between modifying a variable itself and modifying a property of a variable when passing by reference.

Why didn't snippet below changed dog object to null?

Don't they point to the same place in memory(aka passing by reference)?

let dog = {legs: 4}
let human;

human = dog;
human = null;

console.log(dog, human) // { legs: 4 } null

Below, on the opposite, changing a property legs within the variable changes both variables:

let dog = {legs: 4}
let human;

human = dog;
human.legs = 2;

console.log(dog, human) // { legs: 2 } { legs: 2 }

Can somebody kindly explain or point me to the right direction to read more about this issue.

Roma Kim
  • 321
  • 1
  • 8
  • JavaScript is *always* pass-by-value. Re-assigning a variable does not modify any other variables that might have the same data. If you write my name on two pieces of paper, they both contain a value that's a reference to me. If you then crumple up and throw away one of those piece of paper 1. the other one still exists 2. I don't disappear into nothingness – VLAZ Sep 23 '22 at 05:30

0 Answers0