Monday, May 31st, 2010
Kangax then came up with a fantastic comment to discuss it all, starting with:
`1 + + 1` is parsed as an addition operator (`+`) applied to expressions `1` and `+ 1`. It’s functionally identical to `1 + (+ 1)`. Expression on the right-hand side — `+ 1`, in its turn, is nothing but a unary `+` operator applied to `1` (numeric literal 1). Unary `+` converts operand to a number type, but since `1` is already of number type, `+1` is practically a no-op, and evaluates to `1`. The whole expression is functionally identical to `1 + 1` and therefore evaluates to `2`.
`1 + – + 1` is very similar to the one from the first example. It’s an addition operator (+) applied to expressions `1` and `+ – + 1`. This right-hand side expression — `+ – + 1` is a unary operator (+) applied to unary operator (-) applied to unary operator (+) — all starting from the “inner” `+` (the one closer to the right).
`+ – + 1` is functionally identical to `+(-(+(1)))`, which first converts `1` to number, then negates its sign (result of unary operator), then converts operand to number again. It is therefore functionally identical to just `-1`. The whole expression becomes `1 + (-1)` and so evaluates to `0`.
I saw this at Brian Leroux’s updated WTFJS, which is now open source. What is cool is that it runs on the new Heroku node service, which brilliantly means that you can have your own WTF moment by simply:
- Fork the code $ git clone http://github.com/brianleroux/wtfjs
- Run the app: $ node server.js
- Push to your own production: $ git push heroku master
Posted by Dion Almaer at 1:16 pm