Given javascript syntax will do what? [duplicate] - javascript

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I started JavaScript programming last month, i know basic syntax like objects, functions, class, string, array, property. Now i was puzzled on given syntax.
Syntax:
(function(){
"use strict";
})();
My question is, why two parenthesis( one contains 'function' and another "empty" ) are included in the definition? can some one help me why we use this?.

That will create an anonymous function and then immediately execute it.
In this case that function has a single line..."use strict".

That code doesn't have any net impact on the world. What happens is:
The parenthesized function is instantiated;
The final () cause that function to be called;
The "use strict" constant turns on "strict" mode;
The function returns.

What you have there is a self-invoking function.
It pretty much is exactly that, a function which immediately gets called. To accomplish that, we need a function expression, not a function declaration. To achieve that, we can do certain things, one of those is, to put the whole expression in parenthesis
(function() {});
this statement creates a function expression. Now all we have left to do is, to invoke that function by appending additional function parenthesis, like we would do with any function
(function() {})();
You can also put the function parenthesis into the whole statement, it makes no difference
(function() {}());
Another option to bring a function into an expression form is by using ! or + signs infront of it
!function(){}()
Anything goes, as long we create an expression, we can't invoke a function declaration like that
function foo(){}() // syntax error

This is a self-invoked anonymous function (or immediately invoked function expression, also known as IIFE), a pattern that in this case exists just to produce a closed scope.
Apparently, they don't want "use strict"; turning on strict mode for the whole file, or when minified and concatenated to other files, turning on strict mode on included libraries, etc. Amazon had a problem with this a while back. Since then, it's been recommended best practice to keep "use strict" in function scope, and this function exists solely for that purpose.

Related

Why are parentheses required around JavaScript IIFE? [duplicate]

This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 7 years ago.
I'm reading up on JavaScript IIFE and so far the understand concept, but I am wondering about the outside parenthesis. Specifically, why are they required? For example,
(function() {var msg='I love JavaScript'; console.log(msg);}());
works great, but
function() {var msg='I love JavaScript'; console.log(msg);}();
generates a syntax error. Why? There are lots of discussions on IIFE, but I'm not seeing a clear explanation about why the parentheses are required.
There are two ways to create functions in JavaScript (well, 3, but let's ignore new Function()). You can either write a function declaration or write a function expression.
A function declaration in itself is a statement and statements by themselves don't return values (let's also ignore how the debugging console or Node.js REPL print return values of statements). A function expression however is a proper expression and expressions in JavaScript returns values that can be immediately used.
Now, you may have seen people saying that the following is a function expression:
var x = function () {};
It may be tempting to conclude that the syntax:
function () {};
is what makes it an expression. But that's wrong. The syntax above is what makes it an anonymous function. And anonymous functions can either be a declaration or an expression. What makes it an expression is this syntax:
var x = ...
That is, everything to the right of an = sign is an expression. Expressions make it easier to write math formulas in programming languages. So in general everywhere that math is expected to be processed is an expression.
Some of the forms of expressions in JavaScript include:
everything to the right of an = operator
things in braces () that are not function call braces
everything to the right of a math operator (+,-,*,/)
all the arguments to the ternary operator .. ? .. : ..
When you write:
function () {}
it is a declaration and does not return a value (the declared function). Therefore trying to call the non-result is an error.
But when you write:
(function () {})
it is an expression and returns a value (the declared function) which may be used immediately (for example, may be called or may be assigned).
Note the rules for what counts as expressions above. From that it follows that braces are not the only things that you can use to construct an IIFE. Below are valid ways for constructing IIFEs (because we write function expressions):
tmp=function(){}()
+function(){}()
-function(){}()
0/function(){}()
0*function(){}()
0?0:function(){}()
(function(){}())
(function(){})()
You may actually see one of the above non-standard forms (particularly the + version) in third-party libraries, because they want to save one byte. But I strongly advise you to only use the brace forms (either are fine), because they are widely recognized as IIFEs by other programmers.
The version of IIFE that is wrapped in parenthesis works, because this marks the declaration of the internal function declaration as an expression.
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
For more detailed explanation please see:
Advanced JavaScript: Why is this function wrapped in parentheses?
HINT:
The invocation operator (()) only works with expressions, not declarations.
This will be a long-winded answer, but will give you the necessary background. In JavaScript there are two ways functions can be defined:
A function definition (the classical kind)
function foo() {
//why do we always use
}
and then the more obscure type, a function expression
var bar = function() {
//foo and bar
};
In essence the same thing is going on at execution. A function object is created, memory is allocated, and an identifier is bound to the function. The difference is in the syntax. The former is itself a statement which declares a new function, the latter is an expression.
The function expression gives us the ability to insert a function any place where a normal expression would be expected. This lends its way to anonymous functions and callbacks. Take for instance
setTimeout(500, function() {
//for examples
});
Here, the anonymous function will execute whenever setTimeout says so. If we want to execute a function expression immediately, however, we need to ensure the syntax is recognizable as an expression, otherwise we have ambiguity as to whether of not we mean a function expression or statement.
var fourteen = function sumOfSquares() {
var value = 0;
for (var i = 0; i < 4; i++)
value += i * i;
return value;
}();
Here sumOfSquares is immediately invoked because it can be recognized as an expression. fourteen becomes 14 and sumOfSquares is garbage-collected. In your example, the grouping operator () coerces its content into an expression, therefore the function is an expression and can be called immediately as such.
One important thing to note about the difference between my first foo and bar example though is hoisting. If you don't know what that it is, a quick Google search or two should tell you, but the quick and dirty definition is that hoisting is JavaScript's behavior to bring declarations (variables and functions) to the top of a scope. These declarations usually only hoist the identifier but not its initialized value, so the entire scope will be able to see the variable/function before it is assigned a value.
With function definitions this is not the case, here the entire declaration is hoisted and will be visible throughout the containing scope.
console.log("lose your " + function() {
fiz(); //will execute fiz
buzz(); //throws TypeError
function fiz() {
console.log("lose your scoping,");
}
var buzz = function() {
console.log("and win forever");
};
return "sanity";
}()); //prints "lose your scoping, lose your sanity"

What is this pattern's name / purpose? [duplicate]

This question already has answers here:
What do empty parentheses () after a function declaration do in javascript? [duplicate]
(4 answers)
Closed 9 years ago.
I didn't find a post asking for a pattern similar to this one, sorry if I missed it.
Anyway, I'm repeateadly seeing this pattern in many jQuery plugins or scripts:
(function () {
...........
}());
What's its purpose? Does it have a name?
Thanks!
It's also known as an Immediately Invoked Function Expression
Ben Alman has a good article covering IIFE usage, and why "self-executing anonymous function" isn't the best terminology:
One of the most advantageous side effects of Immediately-Invoked
Function Expressions is that, because this unnamed, or anonymous,
function expression is invoked immediately, without using an
identifier, a closure can be used without polluting the current scope.
[... T]the term “self-executing” is somewhat misleading, because it’s
not the function that’s executing itself, even though the function is
being executed. Also, “anonymous” is unnecessarily specific, since an
Immediately Invoked Function Expression can be either anonymous or
named. And as for my preferring “invoked” over “executed,” it’s a
simple matter of alliteration; I think “IIFE” looks and sounds nicer
than “IEFE.”
It's a an immediately invoked function expression (Fiddle):
(function () {
alert("pee");
}());
It is an Immediately-Invoked Function Expression.
It's useful for creating a scope for its contents to enjoy.
It's similar to this:
function myFunc() {
//code
}
myFunc();
But there are 2 differences:
The function is named here
The above code is a function declaration, different from a function expression. 'myFunc' above gets stored as a variable unless you use it as an expression, like so:
foo(function myFunc() {
//code
});
Then it will not get stored as a variable.
It's a immediately-invoked function - as soon as you declare it, it gets evoked.
The () syntax in Javascript means "call this function with whatever arguments are between ( and ). Since there isn't anything between the parentheses in your example, no arguments are supplied to the function call; but if you need to supply arguments, you can do something like this:
(function foo(arg1, arg2) {
alert(arg1 + " " + arg2);
})(3, 5);
Which will immediately call foo() and pass in 3 and 5 as the two arguments.

JS: What's the difference between a ! closure and () closure? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does the exclamation mark do before the function?
So I was going back and looking over some of my own code as well as some other javascript code and I realized that a while back when I started writing javascript libraries I was using closures that looked something like this:
(function( window, document, undefined ) {
// code
})( window, document );
But then I saw some bootstrap code and I changed to this syntax:
! function (window, document, undefined) {
// code
}(window, document);
Now, if I'm not wrong (and please correct me if I am), placing the '!' in front of my anonymous function just causes it to be treated as '()' then returns (into nowhere?) a boolean value of whether the value returned by the function was not undefined, null, or empty.
What I'm wondering is, is there really a difference between using the '!()' syntax over '()()'? Are there certain browsers that will complain?
Any thoughts are appreciated, thanks! XD
What you're asking about is self-calling functions, otherwise known as IIFE (immediately invoked function expression). Which is a different thing from a closure. Although it does create a closure (indeed, all functions in javascript create closures, not just IIFE).
It's understandable that you may confuse the two issues though, since IIFE are usually introduced in the context of explaining closures. But be aware that they are different things. Closures are private, shared "global-like" variables. IIFE are functions that gets called immediately upon their definitions.
Now, how does IIFE work? The clue is in the name. It's the "FE" IIFE - function expression.
In javascript, as you know, there are two ways of creating functions - using function declarations:
function foo () {}
and using function expressions:
foo = function () {}
A function expression is simply a function declared in the context* of an expression. What are expressions in javascript? Simply any statement that evaluates something.
Traditionally, people recognize expressions as:
anything on the right side of the = sign
a = /* expression */
anything in braces
(/* expression */)
So traditionally those are the two "standard" ways for declaring function expressions:
foo = function(){}
and
(function(){})
And the second syntax makes it easy to then execute the function object returned by the expression. But, really, an expression is anywhere js does math (or logic, which is math anyway). So adding an operator to a function declaration also turns it into an expression. The following works because they are unary operators (meaning, they are legal without anything on the left hand side):
!function(){}()
+function(){}()
-function(){}() // I especially like this one because it
// looks like a command line switch
typeof function(){}()
But you can also use binary operators if you use some throw-away value or variable with it. The following also work:
x=function(){}()
0==function(){}()
1*function(){}()
2/function(){}()
Heck, you can even abuse the ternary operator:
0?0:function(){}() // valid and works!
There's nothing magical about it. It's not a specific syntax baked into javascript. Just like (function(){}()) is not a specific syntax for IIFE. It's just that when declared in an expression, functions return themselves as objects which can be called immediately.
But I'd advise against using any of the non-standard forms above though. For the same reason you asked this question - most javascript programmers are not used to seeing them and it can cause confusion. I myself didn't realize that you can do this until you asked the question. Still, it's a useful thing to know for when you need to write things like minifiers, code generators etc.
* I'm using "context" in it's traditional definition here not the javascript specific meaning of "context" as defined in the spec.
Nothing, they are just two different ways of achieving the same thing. The () is slightly more readable though.

Difference between these 2 javascript closure syntaxes? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there a difference between (function() {…}()); and (function() {…})();?
I've seen the following syntax used to prevent variables from getting into global scope:
(function ($, undefined)
{
})(jQuery);
More recently I've seen code doing it this way:
(function ($, undefined)
{
} (jQuery));
I find the 1st way makes the most sense to me. I mentally read it as:
I've defined a function and I wish to wrap it into an expression, (the first set of parenthesis). That expression is a function object which I then wish to call using method syntax and the parameter I'm passing to this function object is jQuery.
The 2nd syntax is less clear to me, because it looks like the outer parenthesis are unnecessary.
My javascript knowledge isn't quite good enough yet to feel comfortable w/ the 2nd syntax.
Do these produce identical behavior? Is there any difference at all?
What would happen if you did this?
function ($, undefined)
{
} (jQuery);
If a function keyword occurs at the start of a line it is parsed as a function statement declaration. Funcsion statements require a function name so the 3rd option you present is not allowed (you can test that yourself).
If the function keyword appears elsewhere it is parsed as a function expression and is allowed to be anonymous. There are many ways to do this but the convention for the module pattern you shown is wraping the construct in parenthesis. (Some byte-savers like using a unary operator like + or ~ instead)
If you choose to use the parenthesis puting the last one inside (1st version) or outside (2nd version) is a matter of personal preference. I prefer the 2nd one since the parenthesis wraps the whole pattern instead of just the function.
The reason you're seeing it done the second way is simply a matter of convention. A lot of people run their code through jslint.com (or node-jslint). By default, the lint tool will complain about the first version of the immediate function.
To see this in action, paste the following code into the textarea at jslint.com and run the tool:
/*jslint devel: true, browser: false, sloppy: false, maxerr: 50, indent: 4 */
(function (a) {
'use strict';
alert(a); // Yay!
}("Yay!"));
(function (b) {
'use strict';
alert(b); // Yay!
})("Yay!");
Yes these are functionally the same. Use whichever one seems more intuitive to you.

What do parentheses surrounding an object/function/class declaration mean? [duplicate]

This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 8 years ago.
In the YUI library examples, you can find many uses of this construct:
(function() {
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event,
layout = null,
...
})();
I think the last couple of parentheses are to execute the function just after the declaration.
... But what about the previous set of parentheses surrounding the function declaration?
I think it is a matter of scope; that's to hide inside variables to outside functions and possibly global objects. Is it? More generally, what are the mechanics of those parentheses?
It is a self-executing anonymous function. The first set of parentheses contain the expressions to be executed, and the second set of parentheses executes those expressions.
It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.
See:
http://en.wikipedia.org/wiki/Closure_%28computer_science%29
http://peter.michaux.ca/articles/javascript-namespacing
Andy Hume pretty much gave the answer, I just want to add a few more details.
With this construct you are creating an anonymous function with its own evaluation environment or closure, and then you immediately evaluate it. The nice thing about this is that you can access the variables declared before the anonymous function, and you can use local variables inside this function without accidentally overwriting an existing variable.
The use of the var keyword is very important, because in JavaScript every variable is global by default, but with the keyword you create a new, lexically scoped variable, that is, it is visible by the code between the two braces. In your example, you are essentially creating short aliases to the objects in the YUI library, but it has more powerful uses.
I don't want to leave you without a code example, so I'll put here a simple example to illustrate a closure:
var add_gen = function(n) {
return function(x) {
return n + x;
};
};
var add2 = add_gen(2);
add2(3); // result is 5
What is going on here? In the function add_gen you are creating an another function which will simply add the number n to its argument. The trick is that in the variables defined in the function parameter list act as lexically scoped variables, like the ones defined with var.
The returned function is defined between the braces of the add_gen function so it will have access to the value of n even after add_gen function has finished executing, that is why you will get 5 when executing the last line of the example.
With the help of function parameters being lexically scoped, you can work around the "problems" arising from using loop variables in anonymous functions. Take a simple example:
for(var i=0; i<5; i++) {
setTimeout(function(){alert(i)}, 10);
}
The "expected" result could be the numbers from zero to four, but you get four instances of fives instead. This happens because the anonymous function in setTimeout and the for loop are using the very same i variable, so by the time the functions get evaluated, i will be 5.
You can get the naively expected result by using the technique in your question and the fact, that function parameters are lexically scoped. (I've used this approach in an other answer)
for(var i=0; i<5; i++) {
setTimeout(
(function(j) {
return function(){alert(j)};
})(i), 10);
}
With the immediate evaluation of the outer function you are creating a completely independent variable named j in each iteration, and the current value of i will be copied in to this variable, so you will get the result what was naively expected from the first try.
I suggest you to try to understand the excellent tutorial at http://ejohn.org/apps/learn/ to understand closures better, that is where I learnt very-very much.
...but what about the previous round parenteses surrounding all the function declaration?
Specifically, it makes JavaScript interpret the 'function() {...}' construct as an inline anonymous function expression. If you omitted the brackets:
function() {
alert('hello');
}();
You'd get a syntax error, because the JS parser would see the 'function' keyword and assume you're starting a function statement of the form:
function doSomething() {
}
...and you can't have a function statement without a function name.
function expressions and function statements are two different constructs which are handled in very different ways. Unfortunately the syntax is almost identical, so it's not just confusing to the programmer, even the parser has difficulty telling which you mean!
Juts to follow up on what Andy Hume and others have said:
The '()' surrounding the anonymous function is the 'grouping operator' as defined in section 11.1.6 of the ECMA spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf.
Taken verbatim from the docs:
11.1.6 The Grouping Operator
The production PrimaryExpression : ( Expression ) is evaluated as follows:
Return the result of evaluating Expression. This may be of type Reference.
In this context the function is treated as an expression.
A few considerations on the subject:
The parenthesis:
The browser (engine/parser) associates the keyword function with
[optional name]([optional parameters]){...code...}
So in an expression like function(){}() the last parenthesis makes no sense.
Now think at
name=function(){} ; name() !?
Yes, the first pair of parenthesis force the anonymous function to turn into a variable (stored expression) and the second launches evaluation/execution, so ( function(){} )() makes sense.
The utility: ?
For executing some code on load and isolate the used variables from the rest of the page especially when name conflicts are possible;
Replace eval("string") with
(new Function("string"))()
Wrap long code for " =?: " operator like:
result = exp_to_test ? (function(){... long_code ...})() : (function(){...})();
The first parentheses are for, if you will, order of operations. The 'result' of the set of parentheses surrounding the function definition is the function itself which, indeed, the second set of parentheses executes.
As to why it's useful, I'm not enough of a JavaScript wizard to have any idea. :P
See this question. The first set of parenthesis aren't necessary if you use a function name, but a nameless function requires this construct and the parenthesis serve for coders to realize that they've viewing a self-invoking function when browsing the code (see one blogger's best-practices recommendation).

Categories