Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Location of parenthesis for auto-executing anonymous JavaScript functions?

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.

The code used to wrap an anonymous function in parenthesis and then execute it,

(function () {   // code here })(); 

but now it wraps the auto-executed function in parenthesis.

(function () {   // code here }()); 

There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”

I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?

like image 448
Kevin Hakanson Avatar asked Aug 02 '10 01:08

Kevin Hakanson


People also ask

What goes in the parentheses of a function JavaScript?

In JavaScript, the functions wrapped with parenthesis are called “Immediately Invoked Function Expressions" or "Self Executing Functions. The purpose of wrapping is to namespace and control the visibility of member functions. It wraps code inside a function scope and decrease clashing with other libraries.

How do you use parentheses in JavaScript?

Parenthesis are used in an arrow function to return an object. Parenthesis are used to group multiline of codes on JavaScript return statement so to prevent semicolon inserted automatically in the wrong place.

Where should functions be placed in JavaScript?

JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked. JavaScript in body: A JavaScript function is placed inside the body section of an HTML page and the function is invoked when a button is clicked.

Which of the following is an example of an anonymous function in JavaScript?

function hello() { alert('Hello world'); } hello(); Anonymous function definition: var anon = function() { alert('I am anonymous'); } anon();


1 Answers

They're virtually the same.

The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.

The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.

I don't think there's a "right" way of doing it, since the result of the expression is the same.

> function(){}() SyntaxError: Unexpected token ( > (function(){})() undefined > (function(){return 'foo'})() "foo" > (function(){ return 'foo'}()) "foo" 
like image 67
meder omuraliev Avatar answered Oct 02 '22 07:10

meder omuraliev