This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 8 years ago.
Difference between the two functions:
(function($){
console.log($);
}("test"));
(function($){
console.log($);
})("test");
I've tried it out on the web console and pressed 'Run'. They return the same thing. What exactly is the difference with the change of parenthesis location?
I am assuming that the second one is run immediately, right?
The two snippets are identical; neither function returns a value and both log their argument to the console. Similarly, both anonymous functions are called with the argument "test".
The only difference is in syntax, regarding the grouping of the function definition vs its application to its arguments. The first function groups the function definition along with the () operator, whereas the second function groups the function definition separately from its application.
Ultimately there is no semantic difference. Both snippets contain an anonymous function which logs its argument and is then called with the argument "test".
The only difference I can think of is if you assign a variable to a function inside the first set of parentheses, you will get different results, depending on the grouping.
var test;
(test = function(arg) {
console.log(arg)
})('I am the argument!')
That works as expected: It assigns 'test' to the function, then runs it once with the argument in the second set of parentheses. It's the same as setting test, then running it with test('I am the argument!')
But how about the other way?
var test;
(test = function(arg) {
console.log(arg)
}('I am the argument!'))
test is undefined! Why? Because when you put the parentheses right next to the function, it invokes the function before it then assigns it to the variable. If you wrap the assignment in parentheses then run it (example 1) then you're good to go.
There is absolutely no difference.
In first case you give "test" value to your function without scopes and there isn't making any difference. In both ways it will working in same way.
Related
This question already has answers here:
In JavaScript, does it make a difference if I call a function with parentheses?
(5 answers)
Closed 6 years ago.
I am just starting to learn javascript while reading a book about node.js. In one of the first examples it shows a high-order function:
setTimeout(function () {
console.log('2000 milliseconds have passed since this demo started');
}, 2000);
This works when I run it in the REPL. It waits 2 seconds and then writes the string I gave it.
So I tried doing something that I expected would produce the same output:
setTimeout(console.log('2000 milliseconds have passed since this demo started'),2000);
This printed the string out immediately. I am guessing that the setTimeout still waited and then did nothing at the end of the 2 seconds. It just printed the string out first for some reason.
I played around with it a little more and created another function that just prints a string:
function tester() {
console.log('tester function ran');
}
I then called this function inside of setTimeout:
setTimeout(tester(),2000);
It still printed the string in tester() out first and then waited 2 seconds and did nothing else.
I then tried removing the parenthesis:
setTimeout(tester,2000);
This "worked". It waited 2 seconds and then printed out the string in tester().
My question now is what is the difference between tester() and tester in this context? And does this mean that I can't pass arguments to a function inside of the high-order function setTimeout()? If so, why?
My question now is what is the difference between tester() and tester in this context?
foo evaluates as a function.
foo() calls the function (with no arguments) and evaluates as its return value.
And does this mean that I can't pass arguments to a function inside of the high-order function setTimeout()?
No. setTimeout, in the implementation you find in browsers at least, allows you to specify arguments to be passed to the function in the third, fourth, etc arguments of the call to setTimeout. You can also create a new function which does nothing except call the existing function with specified arguments. The bind method makes this easy.
foo is a reference to the function itself, foo() calls the function, being whatever the function returns.
in case of setTimeout(tester(),2000); you are actually calling the method tester. And since it does not have any callback, it would not do anything.
setTimeout expects a callback method as a first parameter and that's what is getting passed when you call setTimeout(tester,2000);.
Essentially, you are referring to method definition when you just specify name. However tester() is method call.
see the below style of defining method. That's way it's clearer that tester is actually method definition:
var tester = function(){
}
Hope this helps.
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does this “(function(){});”, a function inside brackets, mean in javascript?
javascript anonymous function
(function())()
this is used in many js library like jquery,YUi
Thats called Module Pattern. The idea is to have an encapsulated module, that cannot conflict with any other modules you or someone else has created. You can create public and private methods within that module.
See: Js Pattern
I'm not sure what (function())() means, but I'll work on the assumption that you meant (function() { … })(). It is roughly the same as:
f = function() { … }; // Define a function.
f(); // Call it.
The only difference is that it does so without requiring a variable.
It is an anonymous self executing function. It is anonymous, because it is not named, and self executing, so it runs (there would be no other way to run an un-named function).
It is particularly useful to enclose a discreet module of code, because it acts as a closure preventing variables leaking into the global namespace.
You're immediately calling an anonymus function with a specific parameter.
An example:
(function(name){ alert(name); })('peter') This alerts "peter".
In the case of jQuery you might pass jQuery as a parameter and use $ in your function. So you can still use jQuery in noConflict-mode but use the handy $:
jQuery.noConflict() (function($){ var obj = $('<div/>', { id: 'someId' }); })(jQuery)
It simply executes the code wrapped in parentheses right away (the first block returns a function, the second pair of parens executes it).
Take for instance these two snippets:
function foo() {
print 'foo';
}
(function() {
print 'foo';
})();
The first won't do anything until you call foo(); whereas the second will print 'foo' right away.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}
Way 1:
function fancy_function(){
// Fancy stuff happening here
}
Way 2:
var fancy_function = function(){
// Fancy stuff happening here, too.
}
I use the former when I'm just defining a "normal" function that I'm gonna use one or several times and the latter when I'm passing it a callback for another function or so, but it looks to work fine in the both ways.
Is it really a difference in some way?
There is no difference to the function itself, but the latter gives you more flexibility as you have a reference to the function and it is different with regard to how it behaves if overwritten.
This allows you to achieve behaviours with the latter that you cannot achieve with the former; such as the following trick to "override" an existing function and then call the "base":
var myOriginalFunction = function() {
window.alert("original");
}
var original = myOriginalFunction;
var myOriginalFunction = function() {
window.alert("overridden");
original();
}
myOriginalFunction();
This gives you an alert "overridden", followed by an alert "original".
However, if you attempt this with the former notation, you'll find you get stuck in a never ending loop of alert "overidden".
In the first sample you are defining a named function -- that function will always be known by that name. Defining a different function with the same name will be an error (unless you assign to the window property directly). In the second sample, you are defining an anonymous function and assigning it as the value of a variable. You can change the value of the variable to any other function later as desired; losing, of course, any reference to the anonymous function in the process unless you've stored it elsewhere. So, you're not really doing the same thing in both cases, though you can treat it that way if you wish -- and make sure to define the function before it's used in the second case, though that's more a function of variables than functions per se.
function definition
function literal assignment
only difference is you can access the former instantly in certain cases whereas you have to wait for the assignment on the latter.
Don't run this in firebug console/interpreter to test it, rather test on a real html page.
say('spotted');
function say(msg){ alert(msg) }
The above will work, but if you defined a function literal with var say = function(){} below, it would complain that it isn't defined yet.
You can use either depending on the situation, both become the methods of the window object. The later is known as anonymous function.
As far as the function is concerned, they will behave identically.
See here for more details: http://javascript.about.com/library/blfunc.htm
Functions defined with the Function(){} style are available throughout the program, without having to be defined earlier in the code than where they are called. It's called 'hoisting', I believe.
so this works
cow('spotted');
function cow(color){ return 'cow is '+color; }
but this throws an error
cow('spotted');//cow isn't defined yet!
var cow=function(color){ return 'cow is '+color; }
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).