Why does this function return "fail"?. Interesting!

Why does this function return "fail"?. Interesting!
0

#1
function whatdoesitdo(){

return (![]+[])[+[]]+(![]+[])[+!+[]]+
([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]];

}

#2

You have to break it down into pieces which are then concatenated together to form the string ‘fail’.

I have re-written the return statement (see below) so that each letter has a separate line. Also, I have added space in certain places to make it easier to see the smaller parts.

function whatdoesitdo(){
  return ( ![]+[] )[ +[] ] + // 'f'
         ( ![]+[] )[ +!+[] ] + // 'a'
         ( [![]]+[][[]] )[+!+[]+[+[]]]  + // 'i'
         ( ![]+[] )[ !+[]+!+[] ]; // 'l'
}

Most of what I have written below is just a guess. I may be incorrect about the why and if so, I hope someone can help better explain it. I will walk you through the first 2 letters and leave the rest up to you to figure out. You can break down the pieces further if you do not understand what a particular part does. I would recommend some console.log statements to dissect the various parts. The letter ‘i’ is the most involved, but the ‘l’ is similar logic as the ‘f’ and ‘a’. I have seen code like this before which spelled other words and phrases. The whole thing is an exercise of understanding how values get coerced in JavaScript when the + operator is used in combination with other data types.

The first letter ‘f’ is created by the following, because (![ ]+[ ]) evaluates to the string ‘false’ and [+[ ]] the since +[] evaluates to 0, you have ‘false’[0], so the 1st character of the string “false” is “f”.

(![]+[])[+[]]

The second letter ‘a’ is created by the following, because (![ ]+[ ]) evaluates to the string ‘false’ and since +!+[] evaluates to 1, you have ‘false’[1], so the 2nd character of the string “false” is “a”.

(![]+[])[+!+[]] 

#3

http://www.jsfuck.com/