0

I detected I made an error and used "}());" instead of "})();" and the code worked just fine which is how it went undetected. I'm wondering if there is a difference? Due to copy and paste this error is in a lot of separate scripts which makes me worried but confused since ESLint didn't complain. I've tried to find an answer but google doesn't give any results when searching for "}());" and "javascript wrong function closure" gives results hinting that they are both the same, no difference. The functions looks like this:

const fname = (function() {
   const cached_func = ...;
   return function(p1, p2) {
     ...
     return cached_func.apply(this, arguments)
  };
}()); <- The error
Dari_we
  • 111
  • 8
  • 1
    Does this answer your question? [What is the (function() { } )() construct in JavaScript?](https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) – Lewis Jul 29 '20 at 04:34

3 Answers3

0

Yes, the difference is that enclosing your function within ( and ) tokens causes your statement to return the said function, as if you called it by its name. Thus, you're able to append () and immediately execute it.

The following two statements produce the same result:

// 1
function myFunction(){
    console.log("1")
}
myFunction();

// 2
(function myFunction(){
    console.log("1")
})()

It is not possible to call a function immediately after its closing bracket, as it results in an Unexpected token ')' error:

function myFunction(){
    console.log("1")
}() // Uncaught SyntaxError: Unexpected token ')'
Andrei
  • 400
  • 2
  • 6
0

These two forms are identical in functionality. It's purely a stylistic choice which you prefer.

Further read here

Navitas28
  • 745
  • 4
  • 13
0

The purpose of wrapping a function in parenthesis "()" is to namespace and control the visibility of member functions.

It wraps your code inside a function scope.

Where as '()' followed by function declaration is to immediately invoke the function which is often called IIFE