Search code examples
javascriptiife

IIFE beginning with one parenthesis bracket not working


I am looking at IIFE's in javascript, and as far as I was aware it was simply a style choice as to how you write the IIFE, and that both approaches below should work.

  var sum = 0
  (function test(n){
      sum += n
  }(1));
  console.log(sum);

This logs: Uncaught TypeError: 0 is not a function.

Alternatively, when I begin the IIFE with ! it works

var sum = 0
  !function test(n){
      sum += n
  }(2);

  console.log(sum) //logs 2

As you can see when I begin the IIFE with a ! it works as expected. I am very confused now as I thought it was simply a stylistic choice as to how you implemented the IIFE. Can anyone explain?


Solution

  • This has nothing to do with the fact that you are only using one parenthesis, it's the lack of a semicolon at the end of the first line.

    Look at it without the line break to see the problem.

    var sum = 0(function test(n){
      sum += n
    }(1));
    

    If you follow the semicolon-free approach, then you need to guard newlines starting with [ or ( with a semicolon.

    For example:

    var sum = 0
    ;(function test(n){
      sum += n
    }(1))