Why is the function with in parenthesis? [duplicate] - javascript

This question already has answers here:
Why is this function wrapped in parentheses, followed by parentheses? [duplicate]
(6 answers)
Closed 8 years ago.
Question:
Why is the function wrapped in a parenthesis? I have taken this code out of parenthesis and it works with no trouble.
What is the benefit of having the code in a (function() { ...Code Here...})(); like it is in the following example?
Code:
(function() {
"use strict";
// Doesn't work because strict mode
// enforces the fact that the second example shouldn't work
if (true) {
function fn1() {
// This won't run
console.log("doesn't work -- have a great Die Hard Day XIII");
};
fn1();
}
})();
Code Here: What would sending the JQuery word as a parameter do for this namespace. I know that the reason that the function is enclosed in (...) is to create a namespace. I guess a better question would be as to why one would pass in a variable, but I would imagine that would be in case another namespace needed the variable.
( function( $ ) {
// Init Skrollr
var s = skrollr.init({
render: function(data) {
//Debugging - Log the current scroll position.
//console.log(data.curTop);
}
});
} )( jQuery );

I have taken this code out of parenthesis and it works with no trouble.
That’s not correct; it can’t run (or even be parsed) by itself. JavaScript sees function in a place where a function declaration can be and assumes it’s a function declaration. Parentheses are used to force the context to be an expression. The practice is redundant if it’s unambiguously a function literal – say, in a variable declaration – but many find it more readable. There’s a jsHint option to enforce it, for example.

Because then they are calling it:
(function() { ... })();
^^

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 - ( 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).

Two ways of immediate call to anonymous function (function(d){ }() ); and (function(x){ } )(); [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Are “(function ( ) { } ) ( )” and “(function ( ) { } ( ) )” functionally equal in JavaScript?
My question having these special characters, I couldn't find a good answer. (Does anyone know how to search with them?)
I've seen two patterns to immediately calling anonymous functions http://jsfiddle.net/ukqS8/1/
(function(d) {
document.write(d*2);
})(3);
and
(function(x) {
document.write(x*2);
}(3));
The difference being where (3) is placed: inside or outside the closing parenthesis.
I found a good explanation for the second case here:
javascript function vs. ( function() { ... } ());
which I understood as function(x) {...} creates a function object, (3) becomes its argument, and the enclosing () tells the interpreter that what's inside is a statement.
In the first case, it appears to make (function(d) {...}) a statement that somehow is also a function, and then apply (3) to this statement/function.
So, they both appear to execute the same way. Is there really a difference here? Scope (I doubt it)? Is either option preferable?
Your understanding is incorrect.
Those are both function expressions; the placement of the parentheses makes no difference here.
However, there can be a subtle difference.
They execute exactly the same. The difference is only in syntax.

what does !function in Javascript mean? [duplicate]

This question already has answers here:
What does the exclamation mark do before the function?
(8 answers)
Closed 5 years ago.
Sorry for posting this but !function is not google-able and I did not find it in my JavaScript code.
Here is how Twitter uses it:
Tweet
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
from https://twitter.com/about/resources/buttons#
It is short-hand or alternative of self-invoking anonymous function:
(function(){
// code
})();
Can be written:
!function(){
// code
}();
You can also use + instead of !.
If you simply did:
function(){
// code
}();
That will create problems, that's why you need to add ! before it which turns the function declaration into function expression.
Quoting docs, section 12.4:
An ExpressionStatement cannot start with the function keyword because
that might make it ambiguous with a FunctionDeclaration.
To better understand the concept, you should check out:
Function Declarations vs. Function Expressions
they're negating the result, not the function itself:
!function( x ){ return x }( true );
!true
false
In reality, it's a slightly compressed form of:
(function(){}())
since it requires 1 less character. The reason it's needed is that you can't call a function declaration directly, e.g. this is invalid:
function(){}()
but adding the ! at the beginning turns it into a function expression and makes it work.
It's usually used to work around a quirk in the JavaScript syntax. This gives a syntax error:
function() {
}();
It's read as a function declaration (like function foo () {}), rather than a function expression. So adding the ! before it, or wrapping it in parentheses, forces the parser to understand that it's an expression.

Categories

Resources