Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How/why does this javascript code print 'fun'?

Tags:

javascript

alert(
    (![]+[])[[]-[]]+
    (([]+[])+([][[]]))[[]-[]]+
    (([]+[])+([][[]]))[!![]-[]]
);

Heres' the fiddle: http://jsfiddle.net/leeny/6VugZ/

How exactly is this cryptic piece of code working?

like image 341
PhD Avatar asked Mar 08 '13 20:03

PhD


People also ask

Why this is used in JavaScript?

“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.

How do you print a variable in JavaScript?

log() is a function in JavaScript that is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user. Syntax: console. log(" ");

How does this keyword work in JavaScript?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.


1 Answers

        vvvvvvv [0]
(![]+[])[[]-[]]                            = "false"[0]
^^^^^^^^ "false"

                  vvvvvvv again [0]
(([]+[])+([][[]]))[[]-[]]                  = "undefined"[0]
^^^^^^^^^^^^^^^^^^ "undefined"

                  vvvvvvvvv this time [1]
(([]+[])+([][[]]))[!![]-[]]                = "undefined"[1]
^^^^^^^^^^^^^^^^^^ again "undefined"

Thus you get "f"+"u"+"n" === "fun".

Further explanation

"false"

![] is false. +[] simply acts as a transformation into a string. Thus we gain the string "false".

"undefined"

One of the operands needs to be a string. This is being done by []+[]. The actual undefined is created in the right hand side: [][[]] === [][0], the first entry of an empty array is undefined.

like image 94
Zeta Avatar answered Oct 12 '22 18:10

Zeta