0

How are these two pieces of code different from each other? var a = (function() {//code})(); and var a = function () {//code}(); `

I tried to use both the ways in my code and they both worked well. So, it got me confusing as to why we wrap the function declaration of an IIFE in parenthesis? Here is an example where i use both the ways for the same purpose:

let a = (function () {
  let count = 0;
  return {
    increment : function () {
      console.log(++count);
    }
  }
})();
a.increment();
a.increment();
a.increment();

and

let a = (function () {
  let count = 0;
  return {
    increment : function () {
      console.log(++count);
    }
  }
})();
a.increment();
a.increment();
a.increment();
  • 1
    Your two codes are identical... – CertainPerformance Mar 12 '23 at 06:20
  • It's the same. Wrap an IIFE with brackets is simply a way to make it more readable/beautiful/your-word-of-choice, according to some people, including me. – InSync Mar 12 '23 at 06:35
  • Yes, they are same in effect. Some sources stated that `var a = function () {//code}();` is syntactically incorrect which is not the case as it seems to work just fine. – Syed Faheem Mar 12 '23 at 08:41

0 Answers0