Home > Software engineering >  IIFE arrow function assigned to variables is not working
IIFE arrow function assigned to variables is not working

Time:12-14

IIFE can be achieved when dealing with function expression. One rule is that everything after = sign is an expressien so below code works

const iife = function() { return 5 }(); // iife = 5

Why is that this is not working?

const iife = () => 5() or () => { return 5 }();

Why in case of arrow function I need to use parantheses to make it work?

const iife = (() => 5)() or (() => { return 5 })()

Isn't just () => 5 or () => { return 5 } also an expression?

CodePudding user response:

Why is that this is not working?

const iife = () => 5() or () => { return 5 }();

In the former, JS interprets it as you trying to call a function named 5 and return its return value.

In the latter, JS interprets you trying to call an object as a function { return 5 } and returning its return value.

Similarly, when calling an IIFE declared with function, curly braces are required. function a() { return 5 }() will not work, but (function a() { return 5 })() will.

It is necessary to wrap the two in brackets so the whole expression is interpreted as a function when called.

  • Related