shlogg · Early preview
Cassidy Williams @cassidoo

JavaScript Reference Vs Value Assignment Explained

JavaScript assigns objects by reference, not value. When you change an object, it affects all references to that object. Example: `let [CLOSED, OPEN] = [{}, {}]; CLOSED.cake = OPEN;` changes both `CLOSED` and `OPEN`.

I was helping a friend of mine with some technical interview questions, and a lot of them were very much like “what does this code output”-style questions (which I deeply dislike, I think these questions are more indicative of someone knowing really specific aspects of a language and less about software engineering, but I digress). One of them though I thought was interesting enough to write a technical explanation.

  
  
  Values and objects

Look at this JavaScript code:

let [CLOSED, OPEN] = [{}, {}]
CLOSED = {
  cake: OPEN
}
OPEN = {
  fish: 5
}
console.log(CLOSED); // cake is {}...