0

I have a problem which I can't understand. I use js book to learn javascript, and there was an example of the code.

let a = {};
let b = a;
b = a["folder"] = {}; // how to understand this?
// after that b = {}, a = {folder: {} }

Please explain this :(

  • [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+difference+between+copying+primitive+vs+copying+object) of [Modifying a copy of a JavaScript object is causing the original object to change](https://stackoverflow.com/q/29050004/4642212), [JS object copy by value vs copy by reference](https://stackoverflow.com/q/19448646/4642212) and [Why does changing an Array in JavaScript affect copies of the array?](https://stackoverflow.com/q/6612385/4642212). – Sebastian Simon Feb 12 '21 at 12:41
  • Related: [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/q/518000/4642212). – Sebastian Simon Feb 12 '21 at 12:45
  • In short, `{}` is an object in memory, and `a = {}` means that `a` is now pointing at that object. When you now do `b = a`, b is now also pointing at that same object. Thus changing a actually changes the object, and therefore, b is "changed", too. –  Feb 12 '21 at 12:46

1 Answers1

0

The last line in your example is evaluated from right to left, first assigning the value of a['folder] to be a new empty object, and then assigning the value of b to be equal to a['folder'] as a reference to the same object.

This overrides your initial assignment of b = a;

let a = {};
let b = a;
console.log(a === b); // true

b = a["folder"] = {};

console.log(a === b) // false, because b is now a reference to the object assigned to a.folder
console.log(a.folder === b) // true
pilchard
  • 12,414
  • 5
  • 11
  • 23