Difference between (function(){})(); and function(){}(); [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Are “(function ( ) { } ) ( )” and “(function ( ) { } ( ) )” functionally equal in JavaScript?
This is something I haven't quite figured out yet, but I have been using function(){}() just because my VIM syntax highlight screws up if I add the parenthesis, although I've seen (function(){})() around many times, maybe its an IE thing?
edit:
var singleton = function() {
// code
}();
var singleton = (function() {
// code
})();

Peter Michaux discusses the difference in An Important Pair of Parens.
Basically the parentheses are a convention to denote that an immediately invoked function expression is following, not a plain function. Especially if the function body is lengthy, this reduces surprises,

The extra set of parentheses makes it clearer that you are constructing a function and then calling it. It's a coding style thing, not a functionality thing.

function(){}();
doesn't work in most of browsers. You should use parenthesis around the function in order to execute it
(function(){})();
then browser will know that last parenthesis should be applied to all the expression
function(){}
UPD: If you don't use parenthesis, the brower could misunderstand you. If you just call the function and dismiss the result
function() {
alert(1);
}();
then ff and ie will throw error

Related

Arrow function confusion [duplicate]

This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 4 years ago.
I was doing a question on codesignal and when I couldn't get the answer myself for all tests, revealed the answers and saw this one; while I understand what it's trying to do (make sure positions are not divisible by n, and if it is increment n by one) I'm having trouble understanding the arrow function syntax and, rewriting it myself from their code.
function obst(inputArray) {
for (var n=1;;n+=1) if(inputArray.every(x=>x%n)) return n;}
In Javascript, every function written like this:
function(args) {
// DO SOME STUFF
}
can be written like this:
(args) => {// DO SOME STUFF}
In your case, the method .every() expects a function, and
function(x) {
return x%n;
}
is written as
x => x%n
inputArray.every(x=>x%n)
is the same as
inputArray.every(function (x){
return x%n
}))
( except for the way the 'this' keyword works )
For any doubt about Javascript language, i recommend the You Dont Know Js series
written by Kyle Simpson.
It's a very enlightening book.
Tip: When you write a code, ask question to youself like:
what i'm doing?
assigment means equality?
what are the methods that can i use in string variables?
And something like that.
Stimulate yourself to know what in the actual fudge, you are doing.
Cheers!.

Meaning of !function in Javascript self invoking function [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.

Confusion about auto-run functions [duplicate]

This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 6 years ago.
I know what auto-running functions are, I use them very often in both Node.js and simple JavaScript. But I still don't understand something.
I kind of know why the following works
(function () {/* Stuff */})();
But I seriously have no idea why the following works...
(function () {/* Stuff */}());
...while the following doesn't...
function () {/* Stuff */}();
...but this also works...
!function () {/* Stuff */}(); // The "!" can be any valid expression
Can I get a detailed explanation?
If it is javascript
(function () {console.log("hi");})();
This is an Immediately invocable function expression, which mean definition followed by invocation, so as it is getting called immediately it works
function () {console.log("hi")}();
This will throw an error ,because definition is followed by braces,if you want to invoke it make it an IIFE
!function () {console.log("hi")}();
This is because, if you put a unary operator before the function declaration, you need not add closing braces, and it chops off one character of the code.
Hope it helps

Self Invoking functions difference [duplicate]

This question already has an answer here:
What is this javascript syntax? !function(){} [duplicate]
(1 answer)
Closed 7 years ago.
What is the difference between these two self invoking functions? The function does not work if the ! (not) symbol is added.
Please clarify if any one has clear understanding.
// first
(function( $ ) {
// ...
})( jQuery );
// second
!function($){
alert("test1");
}(jQuery), function(){
alert("test2");
}(jQuery);
!function () {} means negative function (similar to if (!someVar) {}), to make sure what result is before making it negative, function must be executed. So ! can be replaced with +.
You have something wrong with //second, because you create two anonymous functions and between there is ,. I think you are getting syntax error in this place, so next function does not work (and is not executed, because no one is calling this function)

What does "!function () {}" mean/do in javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does the exclamation mark do before the function?
! preceding function in javascript?
javascript function leading bang ! syntax
I've been seeing this pattern a little bit recently in javascript:
!function () {
// do something
}()
what does the bang in front of the function keyword supposed to do? I can't seem to find anything about it on the intertubez.
function () {
// do something
}();
This is an immediately invoked function declaration. A function declaration can not be immediately invoked; it is a syntax error.
To get around this syntax error, most people enclose the IIFD in parens to force it to be an expression instead (IIFE).
(function () {
// do something
})();
In this case, they added an exclamation point instead.

Categories