Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the answer 42?

Tags:

I'm trying to understand how this palindrome expression is giving 42. I know about operator precedence rules, but this is beyond my current Javascript level. How can I start?

alert ("The answer is " +

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

);
like image 624
user3097261 Avatar asked Dec 12 '13 22:12

user3097261


People also ask

Is 42 really the answer to life?

The number 42 is, in The Hitchhiker's Guide to the Galaxy by Douglas Adams, the "Answer to the Ultimate Question of Life, the Universe, and Everything," calculated by an enormous supercomputer named Deep Thought over a period of 7.5 million years. Unfortunately, no one knows what the question is.

What does 42 mean in the Hitchhiker's Guide to the Galaxy?

42 (or forty-two) is the Answer to the Ultimate Question of Life, the Universe and Everything. This Answer was first calculated by the supercomputer Deep Thought after seven and a half million years of thought.

Why is the number 42 in so many movies?

The number 42 appears in key scenes throughout "Spider-Man: Into the Spider-Verse," and it's also present in the original comic book. Some fans believed it was a nod to Douglas Adams' book "The Hitchhiker's Guide to the Galaxy," but it's not. It's a reference to baseball legend Jackie Robinson's jersey number.


1 Answers

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, coerced into an integer.

[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, coerced into an integer.

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

like image 60
Jeremy Avatar answered Oct 14 '22 21:10

Jeremy