CoronaVirus
CoronaVirus

Reputation: 421

Alert is not a function inside IIFE

As soon as execution context goes inside IIFE, it says alert is not a function. Is there any specific thing that i need to know about IIFE. or Am i doing something wrong ?

var test = 0;

function makeTest() {
  var test = 10;
  alert(test);
  alert(window.test)
    (function() {
      var test = 20;
      alert(test);
      alert(window.test);
    })();
}
alert(test);
makeTest();
alert(test);

Upvotes: 0

Views: 173

Answers (3)

Quentin
Quentin

Reputation: 943598

It says alert(...) is not a function, not alert is not a function.

Your code is attempting to do this:

alert(window.test)(function () { })();

… as you are falling victim to automatic semi-colon insertion not working the way you expect.

i.e. You are calling the return value of alert() and passing your anonymous function as an argument.

Be explicit about where statements end. Use semi-colons.

var test = 0;

function makeTest() {
  var test = 10;
  alert(test);
  alert(window.test);
  (function() {
    var test = 20;
    alert(test);
    alert(window.test);
  })();
}
alert(test);
makeTest();
alert(test);

Or use let in a block instead of an IIFE:

var test = 0;

function makeTest() {
  let test = 10;
  alert(test);
  alert(window.test)
  {
    let test = 20;
    alert(test);
    alert(window.test);
  }
}
alert(test);
makeTest();
alert(test);

Upvotes: 5

Mitya
Mitya

Reputation: 34556

Oh what a difference a semicolon (or lack thereof) can make.

alert(window.test)
(function() {
  var test = 20;
  alert(test);
  alert(window.test);
})();

Note the missing semicolon after the first alert. Its absence means you are effectively doing jQuery-style chaining of methods - i.e. your code is treating the IIEF as a method of what is returned by the alert. This is easier to visualise in a truncated example:

alert('foo')(function() { /* ... */ })();

Since 'foo' clearly has no method constituting an IIEF, this errors.

Upvotes: 0

Muhammad Nabeel
Muhammad Nabeel

Reputation: 86

Try adding a semicolon after alert(window.test) so your code will look like:

var test = 0; 
function makeTest() {
    var test = 10;
    alert(test);
    alert(window.test);
    (function() {
        var test = 20; 
        alert(test);
        alert(window.test);
    })();
}
alert(test);
makeTest();
alert(test);

Upvotes: 0

Related Questions