Why Self-Executing Anonymous works? [duplicate] - javascript

This question already has an answer here:
Difference in these tiny syntax variations for an IIFE? [duplicate]
(1 answer)
Closed 6 years ago.
I know about Self-Executing Anonymous. And usually we create them as
(function(){ return 1;})()
the reason - parser feature which didn't run if we use
function(){ return 1}()
But today I found that next code works too ( check brackets order )
(function(){ return 1;}())
function(){ return 1; }() still give me SyntaxError, as it should
Please explain why? Thx for reference to get more details
P.S. the question is about (function(){ return 1;}()) variant!

(function() {})()
and
(function() {}())
are equivalent.
To call second example you can include + operator before function
+function(){ return 1 }()
See Immediately-Invoked Function Expression (IIFE)

The phrase IIFE is a better term for these functions .. Immediately Invoked Function Expressions.
As for why they are the same: The outer parens () simply make an expression and the () together do the invocation.
(function(){ return 1;})()
is the same as:
(function(){ return 1;}())
(function(){ return 1;})()
becomes
(functionexpression)()
becomes
functionexpression()
and
(function(){ return 1;}())
becomes
(functionExpression())
becomes
functionExpression()
for the same reason that
(3)+2 is the same as ((3)+2).
EDIT
function(){ return 1; }()
Does NOT work because a function statement is different from a function expression. Function statements cannot be immediately invoked.

Related

Self Invoking Functions [duplicate]

This question already has answers here:
What does the exclamation mark do before the function?
(8 answers)
Closed 4 years ago.
Importance of using ! in this code
var testValue;
!function test() { testValue = 3; }();
console.log(testValue);
The ! indicates to the interpreter to parse what follows as an expression rather than as what would otherwise be a function declaration. Function declarations can't be invoked on the same line, so without the !, a SyntaxError would be thrown:
var testValue;
function test() { testValue = 3; }();
console.log(testValue);
Only function expressions can be immediately invoked. Though, to indicate a function expression, it would probably be clearer to use parentheses around the function rather than !, and there isn't all that much point to naming the function test if the function name isn't used anywhere, eg:
var testValue;
(() => {
testValue = 3;
})();
console.log(testValue);
Functions are not automatically objects. You should define it inside brackets or assign it to a variable. If you use ! for function definition. It means
!(function(){console.log("hi");})
Now you can insert () to run that function.

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 (

Why is the function with in parenthesis? [duplicate]

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() { ... })();
^^

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

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