0

I'm trying to wrap my head around this javascript snippet:

(_=[].concat)()[0]

It returns window, but why?

TimE
  • 2,800
  • 1
  • 27
  • 25
  • If you are interested in different options of obfuscation in JavaScript you may also have a look at this: http://stackoverflow.com/a/16036784/1249581. – VisioN Oct 15 '13 at 09:35
  • @VisioN universal obfuscating tool... awesome stuff.. :D – Psych Half Oct 15 '13 at 09:40

1 Answers1

1

After breaking it down into its components it's easier to understand what's going on.

You can basically rewrite this snippet as:

Array.prototype.concat.call(this)[0]

When you call a function, it gets its this context from the object before the ., so the function call object.toString() will have its this reference set to object. However, when a function doesn't have a containing object, its context will default to the global scope, meaning window in browsers. concat will normally use the existing array context it is called on to use as the base array to concatenate on to, but in this case window is the context, so it is cast into an array and then concat is applied to it, but since nothing is provided to be concatenated, it just returns an array with the context, which is window.

TimE
  • 2,800
  • 1
  • 27
  • 25