I have the following array:
let array = [1, 2, 3, [(4, 5, [(6, 7, 8)], 9, [10])]];
I'm using recursion to loop through and reduce it down to a single array.
To start, I just want to console.log(array)
within the for
loop. So code is:
function reduceArray(array) {
for (let i = 0; i < array.length; i++) {
console.log(array[i])
}
}
Expecting to see 4 elements of:
1
2
3
[(4, 5, [(6, 7, 8)], 9, [10])]
I instead get:
1
2
3
[10]
What's happening here?
You have parens ()
, which you seem to assume do nothing, but they actually do have meaning in JS and most languages. Here, the ()
's mean the ,
is interpreted as comma operators instead of as delimiters for arrays.
3
evaluates to 3
, simple enough.[3, 4]
interprets the ,
as an array delimiter and evaluates to an array with 2 elements.(x(), 3, 5)
interprets the ,
as the comma operator and evaluates to 5
, but also invokes x()
, which may have side affects.[3, (x(), 6)]
interprets the 1st ,
as an array delimiter, interprets the 2nd ,
as the comma operator, and evaluates to [3, 6]
, but also invokes x()
.Here's another example:
let y = 10;
let incY = () => y++;
console.log((incY(), incY(), y));
So returning to your example, when you have [(4, 5, [(6, 7, 8)], 9, [10])]
, that evaluates to [10]
.
The comma operator (,) simply evaluates both of its operands and returns the value of the last operand. MDN, comma operator
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments