1

I don't get why this.array[0] equals 1 if this.array[0] = [(2,1)]? What does Javascript do with the 2 and how do i reach/use it? How does parenthesis work inside arrays?

I'd like to do different things with X if the boolean before it is true or false. this.array[0] = [(true, X)] and this.array[0] = [(false, X)].

N.N.
  • 8,336
  • 12
  • 54
  • 94
tmts
  • 45
  • 2
  • 5

5 Answers5

5

Parenthesis in that context act as a statement with the last item passed being the passed value.

In other words:

(2, 1) === 1

The 2 is evaluated, however, so:

(foo(), bar())

is effectively doing:

foo();
return bar();

What you want in this case is [2, 1]

3

If you use the comma operator inside parentheses, it evaluates both items and returns the second. This is rarely used, but there are two canonical reasons for using the comma operator:

  • Loop Logic

You can use the comma operator to have more complex login in a loop, like this:

for (var i = 0, j = 10; i < a && j > b; i++, j--) {  }
  • Side Effect in Condition

You can use the comma operator to execute a statement before evaluating a condition, like this:

if (DoX(), CheckIfXHasBeenDoneSuccessfully()) {  }

Other than that, the comma operator is basically naff. In your parentheses, (2,1), both 2 and 1 are evaluated and 2 is ignored and 1 is returned. You can use parentheses inside an array, but you will almost never want to put commas inside of the parentheses.

What I believe you want is something like this:

var bool = true; //or false, if you like
if(bool){ this.array[0] = X }
else { this.array[0] = Y }
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
3

its not the parens, its the incredibly arcane comma. What a comma will do is that it will evaluate each expression in turn, and return the result of the last one.

Your snippet is either a bug, or someone being an ass. Its the sort of thing that is only rarely useful, and probably shouldnt even be used in those times due to how confusing it is to people.

Matt Briggs
  • 41,224
  • 16
  • 95
  • 126
1

I think you want array[0] = [2,1].

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
psr
  • 2,870
  • 18
  • 22
0

In javascript, the expression

(2, 1)

evaluates to 1. The parentheses cause the expression 2, 1 to get evaluated before the brackets turn it into an array.

You actually want

this.array[0] = [false, X];
Justin Weiss
  • 1,128
  • 7
  • 10