Pingu
Pingu

Reputation: 646

Why is (([]===[])+/-/)[1] = 'a' and (1+{})[(1<<1)+1] = 'b' in javascript?

Recently I came across an interesting website that illustrates a Javascript Obfuscator: http://bl.ocks.org/jasonsperske/5400283

For example, (([]===[])+/-/)[1] gives a and (1+{})[(1<<1)+1] gives b.

I have tried hard to understand the evaluation sequence of these obfuscated result but was in vain.

Taking (1+{})[(1<<1)+1] as an example, I understand that << is the bitwise shift operator and will return 2, so the expression becomes (1+{})[3]. But then I cannot understand what does it mean by 1+{} and [3].

Google isn't really helpful to this problem as search engines don't like the brackets or slashes very much, so in case there are duplicate questions I'm sorry about that.

Upvotes: 6

Views: 259

Answers (3)

Royi Namir
Royi Namir

Reputation: 148644

It's just obfuscation tricks.

for example :

[]===[] ===> false

and

([]===[])+/-/ ===> "false/-/" ( You could test it in the console by yourself)

So what is (([]===[])+/-/)[1] ? ( second char)

That's right :'a'

You may want to look at this also :

enter image description here

Upvotes: 5

xdazz
xdazz

Reputation: 160893

1+{}'s result is a string "1[object Object]", (1+{})[3] is to get the char of index 3 which is b.

The first example:

[]===[] Comparing two different objects with ===, so the result is false, whose toString result is "false".

/-/ is a regex object, whose toString result is "/-/"

When you do false + /-/, which will concat using the result of .toString(), so the result will be "false/-/", and the second char is a.

Upvotes: 3

Thomas Junk
Thomas Junk

Reputation: 5676

You could go step by step:

(([]===[]))

is simply false. Converted into a string "false/-/"and indexed by [1] gives you the a of the string "false".

The same goes for (1+{}) which results in the string "1[object Object]". And 1<<1+1 is another way of writing 3 so this results in "1[object Object]"[3], which is simply b.

Upvotes: 3

Related Questions