Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immediately invoked function expression without using grouping operator

Tags:

I'm trying to immediately invoke a function without using IIFE pattern (enclosing a function definition inside parentheses). Here I see two scenarios:

  1. When a function declaration is invoked immediately: gives SyntaxError.

  2. When a function expression is invoked immediately: executes successfully.

Example 1: gives SyntaxError

//gives `SyntaxError`  function() {      console.log('Inside the function');  }();

Example 2: Executes without any error

// Executes without any error  var x = function() {console.log('Inside the function')}(); // Inside the function

So, I have these doubts:

  • With this approach, why does it give an error for function declaration but not for function expression?
  • Is there a way we can immediately invoke a function declaration without using IIFE pattern?
like image 641
Aaditya Sharma Avatar asked May 13 '19 08:05

Aaditya Sharma


People also ask

What is the use of immediately invoked function expression?

An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.

What is an immediately invoked function in JavaScript with example?

An Immediate-Invoked Function Expression (IIFE) is a function that is executed instantly after it's defined. This pattern has been used to alias global variables, make variables and functions private and to ensure asynchronous code in loops are executed correctly.

What does IIFE stand for?

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

Does declared function execute immediately?

Function expressions are evaluated during execution. So you can't execute function declarations immediately because even variables don't exist yet and other code that the function might depend on hasn't been executed either.


1 Answers

In your code you don't have name for the function that's the reason for syntax error. Even if you would had name it would have thrown error.

function func(){    console.log('x')  }();

The reason is the function declaration doesn't return the values of the function however when you wrap function declaration inside () it forces it be a function expression which returns a value.

In the second example the function() {console.log('Inside the function')} is considered expression because it's on RightHandSide. So it executes without an error.

Is there a way we can immediately invoke a function declaration without using IIFE pattern

You can use + which will make function declaration an expression.

+function(){    console.log('done')  }()

If you don't want to use + and () you can use new keyword

new function(){    console.log('done')  }

Extra

A very interesting question is asked by @cat in the comments. I try to answer it.There are three cases

+function(){} //returns NaN (+function(){return 5})() //VM140:1 Uncaught TypeError: (+(intermediate value)) is not a function +function(){return 5}() //5 

+function(){} returns NaN

+ acts as Unary Plus here which parses the value next to it to number. As Number(function(){}) returns NaN so it also returns NaN

(+function(){return 5;})() returns Error

Usually IIFE are created using (). () are used to make a function declaration an expression + is short way for that. Now +function(){} is already an expression which returns NaN. So calling NaN will return error. The code is same as

Number(function(){})() 

+function(){return 5;}() returns 5

In the above line + is used to make a statement an expression. In the above example first function is called then + is used on it to convert it to number. So the above line is same as

Number(function(){return 5}()) 

In the proof of statement "+ runs on after the function is called" Consider the below snippet

console.log(typeof +function(){return '5'}());

So in the above snippet you can see the returned value is string '5' but is converted to number because of +

like image 52
Maheer Ali Avatar answered Sep 20 '22 14:09

Maheer Ali