본문 바로가기
✘✘✘ Javascript

[javascript] IIFE(immediately invoked function expression)

by PrettyLog 2022. 7. 12.

Search: javascript parentheses IIFE

tmp=function(){}()

+function(){}()

-function(){}()

0/function(){}()

0*function(){}()

0?0:function(){}()

(function(){}())

(function(){})()

Why are parentheses required around JavaScript IIFE? [duplicate]Ask Question

There are two ways to create functions in JavaScript (well, 3, but let's ignore new Function()). You can either write a function declaration or write a function expression.

A function declaration in itself is a statement and statements by themselves don't return values (let's also ignore how the debugging console or Node.js REPL print return values of statements). A function expression however is a proper expression and expressions in JavaScript returns values that can be immediately used.

Now, you may have seen people saying that the following is a function expression:

var x = function () {};

It may be tempting to conclude that the syntax:

function () {};

is what makes it an expression. But that's wrong. The syntax above is what makes it an anonymous function. And anonymous functions can either be a declaration or an expression. What makes it an expression is this syntax:

var x = ...

That is, everything to the right of an = sign is an expression. Expressions make it easier to write math formulas in programming languages. So in general everywhere that math is expected to be processed is an expression.

Some of the forms of expressions in JavaScript include:

  • everything to the right of an = operator
  • things in braces () that are not function call braces
  • everything to the right of a math operator (+,,,/)
  • all the arguments to the ternary operator .. ? .. : ..

When you write:

function () {}

it is a declaration and does not return a value (the declared function). Therefore trying to call the non-result is an error.

But when you write:

(function () {})

it is an expression and returns a value (the declared function) which may be used immediately (for example, may be called or may be assigned).

Note the rules for what counts as expressions above. From that it follows that braces are not the only things that you can use to construct an IIFE. Below are valid ways for constructing IIFEs (because we write function expressions):

tmp=function(){}()

+function(){}()

-function(){}()

0/function(){}()

0*function(){}()

0?0:function(){}()

(function(){}())

(function(){})()

You may actually see one of the above non-standard forms (particularly the + version) in third-party libraries, because they want to save one byte. But I strongly advise you to only use the brace forms (either are fine), because they are widely recognized as IIFEs by other programmers.

댓글