created by Brian LeRoux & Andrew Lunny. sparodically uncurated by David Trejo.

2012 08 11 Slashes!

What should the following JS yield?

    n = 1
    /1*"\/\//.test(n + '"//')

Should it be true? (It is NaN.)

Using semicolons, on the other hand, makes it behave like you'd expect:

    n = 1;
    /1*"\/\//.test(n + '"//');

(Returns true.)

The fun around this WTFJS comes from trying to understand how this should be parsed, so please have fun experimenting with the snippet of code.

When you're done understanding the different levels on which it plays, read on.

The trick revolves around the different cases in which the slash character has meaning. There are three cases: comments, regular expressions, and division, all of which are meant to be on display here.

In the first, semicolon-free snippet, the first slash on the second line is a division. We divide 1 by 1, multiply it by a long string, and after that there is a comment.

In the second snippet, with semicolons, the second line is a regex, tested against the global variable in the first line, transmuted to a string via concatenation.

An interesting variation that shows what happens more clearly is the following:

    n = 1
    /1?":n\/\//.test(n + '":n//')

That returns ":n///.test(n + '". It gives the trick away. (It uses the ternary operator ?:, if you're wondering.)

Obviously, if you really want your friends to have a headache, give them this version:

    n = 0
    /0?":n\/\//.test(n + '":n//')

That returns undefined, which is even more obscure than the NaN that we got in the first snippet. Yes, 0/0 is NaN, which is falsy.


Fork me on GitHub