Reputation: 2014
I'm modifying a Javascript library which was written by a third party. The code does work for the most part. There are no syntax errors. It will be nearly impossible to ask the author about the code.
I came across this construct, and cannot understand what the programmer intended.
pages[uuid, elIndex] = 12;
Inspecting with Chrome devtools, I see that page is an object. uuid is a string and elIndex is a number.
I can't understand what's intended here with the comma between multiple object properties. Is this some very obscure Javascript syntax? What is meant by accessing "multiple properties" like this?
Upvotes: 0
Views: 36
Reputation: 97656
This:
pages[uuid, elIndex] = 12;
is exactly equivalent to:
pages[elIndex] = 12;
This is the seldom-used comma operator.
Unlike a method call (which takes several arguments separated by commas), the array indexer takes a single expression, so uuid, elIndex
is parsed as a single expression that uses the comma operator. The comma operator evaluates both sides, then throws away the value of the left side and returns the value of the right side. It's occasionally used in for
-loop initializers, and it's used heavily in minified code, but otherwise it really doesn't have a ton of practical applications if you're trying to write readable code.
As Bergi noted in the comments above, the author probably thought this would be a multidimensional array access, but it isn't. It's just pages[elIndex]
.
Upvotes: 2