1.

Why does the following not work as an IIFE (Immediately Invoked Function Expressions) ? What needs to be modified in order for it to be classified as an IIFE?

Answer»

function f(){ }();

The JavaScript parser interprets the function f(){ }(); as function f(){ } and (); where the former is a function declaration while the latter (a pair of brackets) is an attempt to execute a function without specifying a name, resulting in Uncaught SyntaxError: Unexpected token ).

(function f(){ })() and (function f(){ }()) are TWO ways to fix it that involve adding more brackets. These functions are not available in the global scope, and you can EVEN omit their names if you don't need to refer to them within the body.

You can also use the void OPERATOR: void function f(){ }(); .However, there is a drawback in this strategy. Because the evaluation of a given expression is always undefined, you can't use your IIFE function if it returns anything. Consider the following SCENARIO:

// Don't add JS syntax to this code block to prevent Prettier from formatting it.const f = voidfunction b() { return 'f';}();console.log(f); // undefined


Discussion

No Comment Found