Hongbo Miao Hongbo Miao - 2 months ago 4
Javascript Question

How does two continuous equal in JavaScript work?

Basically, the line of code

curr = curr[ch] = curr[ch] || {}
sets variable
ch
as key of the object and set
{}
as the value of the object, then point to its child reference.

But can someone explain in detail how it works? Thanks

http://jsbin.com/gokapoc/1/edit?js,console

let root = {};
let curr = root;

let ch = 'a';
curr = curr[ch] = curr[ch] || {};
ch = 'b';
curr = curr[ch] = curr[ch] || {};
ch = 'c';
curr = curr[ch] = curr[ch] || {};

console.log(root);


It will show the result:


{
a: {
b: {
c: {}
}
}
}


Answer

Let’s do a walk through. I added parentheses to make things more clear – they don’t change the meaning.

let root = {};
let curr = root;

Nothing difficult until now

let ch = 'a';
curr = (curr[ch] = (curr[ch] || {})); 

Okay, so curr[ch] is undefined at the moment because there’s no property a (ch’s value at the moment) in curr which points to the same object as root. Therefore the most inner parentheses evaluates to {}.

This value is assigned to curr[ch]. So obviously there’s a property a in the root object now.

Finally, this object (root.a) is assigned to curr, because the assignment in the outer parentheses returns the assigned value, which is the object at property a.

ch = 'b';
curr = (curr[ch] = (curr[ch] || {}));

Basically the same as before, just important to note that curr is not root here but the same object to which root.a points. In the end curr will point to the same object as root.a.b.

ch = 'c';
curr = (curr[ch] = (curr[ch] || {}));

Yeah, and this should be clear by now.

Very compact but not very clear code.

Comments