Reputation: 89
I'm reviewing some code and can't figure out what this means:
(attrs = {})[key] = val;
key
and val
are both string variables.
Is it a shortcut for an if condition? An object declaration?
Upvotes: 0
Views: 69
Reputation: 61875
(attrs = {})[key] = val;
is equivalent to
attrs = {};
attrs[key] = value;
That is, the variable assignment in the expression happens first and then the object (the result of the assignment) is modified via a normal property assignment.
I would personally use the latter form here.
Upvotes: 4
Reputation: 82277
Similar to math, in javascript, anything that happens in ()
will go occur first. The exception is in function definitions which are strictly for declaration.
The expression, as denoted by ()
will execute prior to the rest of the code and return the value inside. This is used in multiple places such as immediately executing function expressions, or in places where a comma is used to build a return value in an expression.
In your case, the (attrs = {})
expression will return an object, while also assigning that object to the variable attrs. The next code will act on that returned object, accessing a property of the object through []
notation at key
and then assigning that to value
.
Upvotes: 1