Monday, May 31st, 2010

1 + – + + + – + 1. Binary solo? WTFJS!

Category: JavaScript


Thomas Fuchs discussed more fun with JavaScript.

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
  • Run the app: $ node server.js
  • Push to your own production: $ git push heroku master


Related Content:

Posted by Dion Almaer at 1:16 pm

1 rating from 1 votes


Comments feed TrackBack URI

I just can’t wait for all the frameworks out there to implement this powerful feature!

Javascript just keeps getting better and better. Its a rush in itself being a witness to this raging evolution.

Comment by rasmusfl0e — May 31, 2010

Oh? You can do weird stuff in JS for absolutely no reason at all? Stop the presses!

Comment by okonomiyaki3000 — May 31, 2010

Pressed for content by any chance?

Comment by sixtyseconds — June 1, 2010

I’d love to see the JSLint message for that code, I imagine it to go something along the lines of: “Warning :1:1: Worst code ever expected Douglas crockford is now on his way to punch you in the face.”

Comment by simon000666 — June 1, 2010

Leave a comment

You must be logged in to post a comment.