Search code examples
javascriptcompatibility

Is there a name for this construct and has it always been supported?


I am using this JavaScript construct:

new Function('return true;')();

I wonder if there is a name for it (calling the newly created Function object directly).

I checked the precedence and it's ok.

I also wonder if this code will work in old browsers?


Solution

  • I have seen this pattern as Immediately Invoked Function Expression (IIFE)

    It's more commonly used like:

    (function(){return true})()
    

    I'm not sure there is a good reason to use the Function class directly as most use cases can be handled using the normal function declaration methods listed here.

    More information on using Function directly here

    I don't see why it should not work on older browsers but I have not tested it myself