fail

july 1 , 2010

Let's take the last post a step further:


    console.log( (![]+[])[+[]]+(![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]] ) // "fail"

Breaking that mass of symbols into pieces we notices, that the following patten occurs often:


    console.log( (![]+[]) ) // "false"
    console.log( ![] ) // false

So we try adding [] to false. But through a number of internal function calls( binary + Operator -> ToPrimitive -> [[DefaultValue]]) we end up with converting the right operand to a String:


    console.log( [].toString() ) // ""
    console.log( (![]+[].toString()) ) // false + ""

Aha, so we are concatenating strings here! Now this is plain obvious! Moving on to the next bit:


    console.log( [+[]] ) // [ 0]
    console.log( +[] ) // 0

Thinking of a String as an Array we can access its first character via [0]. So "false"[0] returns "f".

I think you got the idea now and can figure out the rest by yourself!

Thanks to Mathias Bynens for pushing this out int the web.


length of what now

july 0 , 2010

This made me laugh. Out loud even!


    console.log((!+[]+[]+![]).length);
    // 9

Huh, wtf?! Lets see what we're getting the length of...


    console.log((!+[]+[]+![]));
    // "truefalse"

Ah! lulz. thanks to @stepiiik and @DavidGrudl!


function in ur string

june 3 , 2010

Old friend (and clearly damaged by a career of JavaScript programming) @jakedevine threw this down on twitter a few days ago.


    var Z = "constructor"; 
    Z[Z][Z]("alert('wtfjs!')")();
    // alerts wtfjs!

Ok. So wtf exactly is happening here?


    Z[Z]
    // function String() { [native code] }

    Z[Z][Z]
    // function Function() { [native code] }

AHA! The constructor property of a string is String and the constructor property of String is Function. Makes sense.


    Z[Z][Z]("console.log('new Function accepts string for eval as argument')")();
    // new Function accepts string for eval as argument

Of course. One wonders, as usual, wtf the programmer was up to when he discovered this!

--- @brianleroux


instances and default values

june 3 , 2010

When you create instances of String or Number, they take the default value ("" for strings and 0 for numbers). This is not the same for Object and Array.


    var a = new Number;
    a == 0 // true

    var a = new String;
    a == "" // true

    var a = new Object;
    a == {} // false

    var a = new Array;
    a == [] // false

This is even more confusing when using the JSON-style syntax to create objects and arrays.


    var a = {};
    a == {} // false

    var a = [];
    a == [] // false

-- @remi

(Never forget: ==== - @brianleroux)


Fork me on GitHub