I'm trying to wrap my head around this javascript snippet:
(_=[].concat)()[0]
It returns window, but why?
I'm trying to wrap my head around this javascript snippet:
(_=[].concat)()[0]
It returns window, but why?
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.