Not sure what to search for here, so apologies if I’m repeating another question.
I’m wondering if there are any issues that I’m not aware of with using the following syntax in JavaScript:
var a = {};
var b = a.niceCoat = {};
Seems handy, but I just want to make sure…
That is perfectly fine, because
awas declared previously. The expressions will be evaluated asI.e. it first assigns a new empty object to
a.niceCoatand the result (the result of an assignment is the assigned value) tob.But be aware of something like
which, again, is evaluated as
Only
awill be in local scope,bwould be global. If you wantbto be local too, you have to declare it beforehand:var b;. Something likevar a = var b = ....does not work (not valid syntax).Slightly off topic:
This method is indeed handy. Imaging you have an object of objects, something like:
and you want to get the object for a certain key or create a new one if the key does not exists. Normally one would probably do:
With the above method, this can be shortened to
And we can make it even shorter with the logical OR operator (
||):(though it might be less readable).