Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why iife not working in a simple example? [duplicate]

I can't understand why functional expression call doesn't work and throws an error.

Can you explain it to me?

var a = function (x) {
  alert(x)
}

(function() {
   a(1);
}());

Thanks to everyone

The task was much easier than I thought

like image 336
Vladislav Khazipov Avatar asked Oct 20 '25 12:10

Vladislav Khazipov


2 Answers

That is because JS is parsing the IIFE as an argument call for the function, do it like this with an added semi-colon

var a = function (x) {
  alert(x)
};    
(function() {
   a(1);
}());
like image 178
olayemii Avatar answered Oct 23 '25 01:10

olayemii


Because at the moment, where you call the function, the assignment has not happened yet.

var a; // hoisted, value undefined, no function

// later

a = function (x) {
    alert(x);
}(function() {
    a(1);      // a is still no function
}());

Or you need to insert a semicolon to separate the assignment from the call,

var a = function(x) {
  console.log(x);
};
(function() {
  a(1);
}());

or take void for separation

var a = function(x) {
  console.log(x);
}
void (function() {
  a(1);
}());
like image 31
Nina Scholz Avatar answered Oct 23 '25 02:10

Nina Scholz