Search code examples
javascriptiife

Call function inside IIFE


let f = function(x) {
  alert(x)
}

(function() {
  f(1)
}())

Why is this code throwing an error? At first, I thought the problem was connected with the incorrect syntax of the IIFE but then I learned that this syntax is also appropriate


Solution

  • This is the one of the rare cases where a semicolon is necessary to separate the function expression from the calling with the following parentheses.

    let f = function(x) {
      alert(x)
    }; // <-------------------
    
    (function() {
      f(1)
    }())