javascriptsyntax

What does `A = (0)['constructor']['constructor']` do?


For an online challenge, I've deobfuscated some code to this:

A = (0)['constructor']['constructor']

From what I've tried, this function takes some code as parameter and puts it in the body of an anonymous function and returns it.

A = (0)['constructor']['constructor']

console.log(A)
console.log(A('return 9'))
console.log(A('return 9')())

However, I don't understand this syntax and how the function is created. What's happening behind the scene ?


Solution

  • There's a surprising amount going on here, so I'll try to break it down into steps.

    So, (0).constructor.constructor is shorthand for Number(0).__proto__.constructor.__proto__.constructor.

    Your anonymous functions that return 9 do what they do because the constructor of a Function accepts as an argument a string representation of some Javascript code. It's equivalent to doing this:

    Function('return 9')();

    Edit: corrected a mistake regarding autoboxing and (0)