1

Provided this code

let myVar = 'hey'
let myVar2 = myVar
myVar = 'what'

When I assign let myVar2 = myVar, I am assigning a reference to myVar2? Or in the assignation myVar gets resolved and I am assigning the value that myVar has at that moment?

My doubt is whether

  • myVar2 holds a reference towards the original myVar (which is no longer available since it has been overwritten by the second assignation myVar = 'what')
  • or myVar2 holds since the beginning whatever value had myVar, regardless that that variable will be overwritten later on
GWorking
  • 4,011
  • 10
  • 49
  • 90
  • 1
    It's always pass by value. `myVar` and `myVar2` never held literally each other. Just content that happens to be similar. – VLAZ May 29 '20 at 10:19
  • 1
    ...however the "value" of a variable that "holds" an array or object is always actually a _reference_ to that object. This reference itself is still handled as a value though, it's not a reference to the previous variable but a reference to the object itself. So: `myVar = {a: 1}; myVar2 = myVar; console.log(myVar === myVar2) /* true */; myVar2.b = 2; console.log(myVar) /* {a: 1, b: 2} */; myVar2 = 'abc'; console.log(myVar) /* {a: 1, b: 2} */;` – CherryDT May 29 '20 at 10:24
  • strings, numbers, booleans, null = value. objects, arrays = reference. undefined is just weird (you can argue it either way - older versions of javascript like the one running on IE7 or Netscape4 would definitely be reference. Newer versions of javascript made undefined immutable) – slebetman May 29 '20 at 10:29
  • @slebetman The `undefined` value is and always was immutable. (Sure, `window.undefined` could be overwritten, but that did not change the value of any variables). – Bergi May 29 '20 at 10:50
  • @CherryDT Even with objects, the variable always holds a reference *value* which references that object. The variable never becomes or holds a reference to another variable. – Bergi May 29 '20 at 10:51
  • Yes, this is why I wrote "This reference itself is still handled as a value though, it's not a reference to the previous variable but a reference to the object itself." in my comment... I just added a clarification because as a beginner it may be confusing to then see objects being mutated. – CherryDT May 29 '20 at 11:30

0 Answers0