JavaScript Operators Challenge Question that I stumbled upon from Stackoverflow and wanted to share it here to have as a fun challenge question.

The question is: In JavaScript, why does this equal 42?

`[(0>>(0==0))+([0]+[(0==0)+(0==0)]^0)]*[(0^[(0==0)+(0==0)]+[0])+((0==0)<<0)]`

Give it some thought. Have you figured it out yet?

Here is the explanation given at StackOverflow

The basic elements are as follows:

**0==0**

This is true, which can be coerced in to 1.

**a >> b**

The right-shift operator. In this case, it’s only used at the beginning of the expression as 0 >> 1 which evaluates to 0.

**a^b**

Bitwise XOR. Both usages above have either a or b are 0, and so the result is the non-zero operand.

**[a] + [b]**

String addition of a and b, evaluates to “ab”; if both a and b are numeric (e.g. [0]+[1] the result can be coerced into a numeric.

**[a] * [b]**

Multiplication can be performed on single element arrays, apparently. So this is equivalent to a*b.

Finally,

**a << b**

The left-shift operator; for positive integers this effectively multiplies by 2 to the power of b. In the expression above, this is used with b = 0, so the result is a.

If you apply the correct order of operations, you get out **[2] * [21]** which evaluates to **42**.

Send it to your friends, see how good they are with JavaScript operators.

## Recent Comments