1

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?

Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
  • 1
    An easy solution is, always add a semicolon before your IIFE, if you prefer not putting semicolon for every line. – Haocheng Mar 17 '16 at 20:24

1 Answers1

1

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))
Dan Prince
  • 29,491
  • 13
  • 89
  • 120