[]['map']['constructor']('console.log(1)')();
Remember JavaScript supports square-bracket- and dot-syntax for interrogating objects.
So the first part is equivalent to
[].map.constructor
...where []
creates a new array. This array inherits (on its prototype) a map()
method, which in turn inherits, on its prototype, a reference to the Function
constructor (since map()
is a function.)
So all of this was just a convoluted route to Function()
. We could replace map()
with any other array method e.g. forEach
or reduce
, or not use arrays at all, e.g.
document['querySelector']['constructor']
...since every method inherits from Function()
.
Now, Function()
allows you to create dynamic functions by passing the body of the function as a string to its first and only argument.So:
var myFunc = new Function('alert("hello from my func");');
This technique is almost never used and comes with the same security risks as eval()
. There's rarely a good reason (or safe way) to evaluate string as code, in any language. (That said, it's worryingly common in frameworks as a means to allow JS-based instructions and syntax in DOM attributes, for example, e.g. Framework7).
In your example, the function being dynamically created is one which logs the integer 1 in the console.
Finally, the trailing ()
immediately executes our created function. It's not assigned to a variable; it's merely executed.