Why write a followup set of empty parenthesis when using IIFE? [duplicate] - javascript

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 7 years ago.
New to JS. Using jonhpapa's Angular style guide and I noticed that when he suggests using the IIFE closure he always adds an extra set of empty parenthesis. Why?
(function() {
'use strict';
angular
.module('app')
.factory('logger', logger);
function logger() { }
})();

To elaborate on my comment - this is an example of a named function:
function x() { console.log('x'); }
In order to invoke the function, you need to add parenthesis after it's name like this:
x();
You do the same thing to unnamed functions in order to invoke them:
(function() { console.log('x'); })();

Related

Are the enclosing parenthesis necessary for anonymous functions? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 5 years ago.
I've seen JavaScript that looks like this:
function () {
// do something
}()
and recently something like this:
(function () {
// do something
})()
Is there any difference? Both are executed immediately correct?
EDIT:
A note about the first example. The function is being passed to the browser from another application so there was no error from my end. It is throwing an error when run in the browser. After digging in, I've found the application API is passing the function to eval. Both examples above work for me which is why I asked this question.
Both of the functions won't execute immediately. An immediately invoked function expression has parenthesis at the end of it as well. Like this:
(function () {
console.log("not hello");
});
(function () {
console.log("hello");
})();
//^^
The parenthesis enclosing the function turn it to an expression which returns the function itself. Then, you just invoke the returned value (which is the function) with (). Take a look at IIFE.
Edit: After your edit, the first function would just throw SyntaxError: Unexpected token (

Javascript: Benefit of naming functions when assigning variables in an object? [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 8 years ago.
I noticed people in my company like to name functions when assigning it to variables. What are the benefits when it works exactly the same without naming them?
function TargetingForm() {
'use strict';
this.setPristine = function setPristine() {
...
}
//vs
this.setPristine = function() {
...
}
}
In order to ensure the name of the function appears in stack traces when debugging (as opposed to showing up as "anonymous function").
However, many modern javascript engines can derive a useful name for stack traces even when the function is declared anonymously in an assignment expression such as in your second example.
One thing that I can think of (if I am right!) is that you might need to call the function from itself (recursion).
For example you can do this:
function TargetingForm() {
'use strict';
this.setPristine = function setPristine() {
// You can do this
if (someConditionIsTrue) {
setPristine();
}
}
//vs
this.setPristine = function() {
// You can't do the same here!
}
}

Javascript - what is the purpose of wrapping functions or codes in a function? [duplicate]

This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
This probably is not a new question, but where is the purpose of wrapping a function or codes inside ((function () {...})());? for instance,
//Self-evoking anonymous functions
((function () {
alert("hi");
})());
What's the difference with no wrap,
alert("hi");
I still get the same result - hi
What can you pass/ put in the brackets in the end bit - })());? and why?
Using a function creates a scope. You can have params inside and do more than just alerting.
Now you can do the same without a function, but then you will keep the state on the window object and thats something that you would like to prevent in some cases.

Awkward way of executing JavaScript code [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Why is this function wrapped in parentheses, followed by parentheses? [duplicate]
(6 answers)
Closed 9 years ago.
In the Google tutorial for implementing Google+ sign-in in Flask application, I discovered that the developer often uses an awkward way of executing JavaScript code:
Instead of doing
var a = foo(bar);
I see this:
var a = (function() {
return foo(bar);
})();
What is the reason to do it the weird way?
This is a poor example. Consider the following:
var a = (function() {
var ret = {};
ret.test = "123";
function imPrivate() { /* ... */ }
ret.public = function() {
imPrivate();
}
return ret;
})();
console.log(a)
a will contain the varible test and the function public, however you can not access imPrivate. This is the common way to handle public vs private variables;
See Why is this function wrapped in parentheses, followed by parentheses? for more info.
var a = (function() {
return foo(bar);
})();
In this case this is really unnecessary, but this is not wrong and it will not throw an error.
But IIF some times uses like module pattern:
var a = (function() {
/* some other code in own scope */
return foo(bar);
})();
In this case IIF is just a module which exports something outside.
The closure function is used to encapsulate some of the attributes / methods in the function. Much like the private / public principle from other languages.
You can find more on this topic here under Module Pattern

JavaScript - ( function () {} () )? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript function vs. ( function() { … } ());
I'm seeing this pattern in several of TodoMVC's JS source:
(function() {
// ...
// ...
}());
What's the specific meaning of this pattern? Note that it is not the self-invoking function which is (function() {})();
What's the specific meaning of this pattern? Note that it is not the self-invoking function which is (function() {})();
You're incorrect, it is an Immediately Invoked Function Expression (IIFE). The parenthesis are just in a different place, but they bind the exact same way.
People often do it in the way you've described to get it to validate JSLint.
It's used for scoping, as JavaScript only has function and global scope (ignoring let).

Categories

Resources