This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 8 years ago.
function foo(bar) {
// ...
}
and
foo = function(bar) {
// ...
};
What is the benefit of one versus the other? The main benefit I see in the latter is not running into errors with a function name already being defined. However, there may be other benefits or drawbacks that aren't obvious. What are they (if any)?
This has been asked a few times, this seems to be the best one.
There are other things that you can do with an anonymous function other than assigning it to a variable. You can for example execute it right away:
(function() { ... })();
This is sometimes used to create a scope for the code. Anything declared in the scope is local to it, and you can return a result to the code outside:
var a = (function() {
var answer = 42;
function display() { window.alert(answer); };
return display;
})();
Now the variable a contains a function that displays the value of the variable answer, but the variable answer is local to the scope:
a(); // displays the value
display(); // not available
window.alert(answer); // not available
This pattern is for example used to create plugins for jQuery:
(function($) {
$.fn.blackText = function() {
return this.css('color', '#000');
};
}(jQuery);
The jQuery object is sent into the scope as the $ parameter, that way the code in the scope can use the $ shortcut even if it has been turned off (using noConflict) outside the scope.
Related
This question already has an answer here:
Named anonymous functions vs anonymous functions
(1 answer)
Closed 2 years ago.
I know this might be a simple question, but I'm learning JavaScript and found these two ways to define functions:
Method 1
var myFunction = function() {
statements
}
Method 2
var myFunction = function namedFunction(){
statements
}
My question is: what is the difference between the name of the variable and the name of the function?
Could I call the second function with myFunction(); and namedFunction(); ?
Thanks for your help!
One difference is that the namedFunction becomes an identifier inside the second function, to refer to the function without having to use the outer myFunction variable name:
var myFunction = function namedFunction(){
console.log('running');
setTimeout(namedFunction, 1000);
};
myFunction();
It's not particularly useful here, since you could just refer to the outer variable, but it becomes more useful when there isn't an outer variable you can cleanly reference, eg:
const obj = {
nested: {
fn: function namedFunction(){
console.log('running');
setTimeout(namedFunction, 1000);
// the above looks cleaner than
// setTimeout(obj.nested.fn, 1000);
}
}
};
obj.nested.fn();
Could I call the second function with myFunction(); and namedFunction(); ?
Yes, both will refer to the function, though the namedFunction identifier will be scoped only inside the function, whereas the myFunction identifier will be scoped anywhere in the outer script.
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
I often see code like the following in JavaScript:
func1: function() {
return array1.pop();
}
What is the difference between the above and something like this:
function func1 (){
return array1.pop();
}
Are the above two the same thing with different way of writing? The first one looks like a switch statement to me. Sorry if this question is too simple but JavaScript books seldom uses the first syntax if this is just the matter of syntax issue; the main reason for me to ask this question in StackOverflow.
The first one is creating a property on an object literal. The property name is func1 and the property value is an anonymous function. For example:
var someObject = {
someProp: function () {
alert('foo');
}
};
someObject.someProp(); // alerts "foo"
For the second one you probably meant function func1 ..., which is a plain old function declaration. For example:
function someFunction() {
alert('foo');
}
someFunction(); // alerts "foo"
Most people use object literals as a way of grouping logical functionality together, similar to namespaces in other languages. By defining functions as properties of other variables, you keep the number of variables in the global namespace down and the code more organized.
The second form is that of a “normal” function declaration: the function is available within the scope in which you’ve declared it. The first form is used inside an object literal:
var myObject = {
func: function() {
return array1.pop();
},
name: 'John Smith'
};
The function can be called as myObject.func() whenever myObject is accessible. Aside from this difference in scoping, the two definitions of the function are equivalent.
There is also a very important difference referred to as "function hoisting" (vague in terms of ECMA, but is a common term to describe the behavior).. This is directly related to the "second way" in original question namely -
function func1 (){
return array1.pop();
}
There are two ways we may use functions (again wrt to second way):
As a function expression -
var a = function() {
}
As a function declaration
function a() {
}
As you know, all variables, no matter where in the function body they are declared, get
hoisted to the top of the function behind the scenes. The same applies for functions
because they are just objects assigned to variables. The only “gotcha” is that when using
a function declaration, the definition of the function also gets hoisted, not only its
declaration.
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
What is the difference between the following lines of code?
//Function declaration
function foo() { return 5; }
//Anonymous function expression
var foo = function() { return 5; }
//Named function expression
var foo = function foo() { return 5; }
Questions:
What is a named/anonymous function expression?
What is a declared function?
How do browsers deal with these constructs differently?
What do the responses to a similar question (var functionName = function() {} vs function functionName() {}) not get exactly right?
They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.
Function declarations load before any code is executed.
Function expressions load only when the interpreter reaches that line of code.
So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.
Example: Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
Example: Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
As for the second part of your question:
var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.
Function Declaration
function foo() { ... }
Because of function hoisting, the function declared this way can be called both after and before the definition.
Function Expression
Named Function Expression
var foo = function bar() { ... }
Anonymous Function Expression
var foo = function() { ... }
foo() can be called only after creation.
Immediately-Invoked Function Expression (IIFE)
(function() { ... }());
Conclusion
Douglas Crockford recommends to use function expression in his «JavaScript: The Good Parts» book because it makes it clear that foo is a variable containing a function value.
Well, personally, I prefer to use Declaration unless there is a reason for Expression.
Regarding 3rd definition:
var foo = function foo() { return 5; }
Heres an example which shows how to use possibility of recursive call:
a = function b(i) {
if (i>10) {
return i;
}
else {
return b(++i);
}
}
console.log(a(5)); // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15
Edit:
more interesting example with closures:
a = function(c) {
return function b(i){
if (i>c) {
return i;
}
return b(++i);
}
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8
The first statement depends on the context in which it is declared.
If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program.
If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()"
EDIT:
I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code.
END EDIT
Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore
var foo = function foo() { return 5; }
Is the same as
var foo = function fooYou() { return 5; }
Though the complete difference is more complicated, the only difference that concerns me is when the machine creates the function object. Which in the case of declarations is before any statement is executed but after a statement body is invoked (be that the global code body or a sub-function's), and in the case of expressions is when the statement it is in gets executed. Other than that for all intents and purposes browsers treat them the same.
To help you understand, take a look at this performance test which busted an assumption I had made of internally declared functions not needing to be re-created by the machine when the outer function is invoked. Kind of a shame too as I liked writing code that way.
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
What is the difference between the following lines of code?
//Function declaration
function foo() { return 5; }
//Anonymous function expression
var foo = function() { return 5; }
//Named function expression
var foo = function foo() { return 5; }
Questions:
What is a named/anonymous function expression?
What is a declared function?
How do browsers deal with these constructs differently?
What do the responses to a similar question (var functionName = function() {} vs function functionName() {}) not get exactly right?
They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.
Function declarations load before any code is executed.
Function expressions load only when the interpreter reaches that line of code.
So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.
Example: Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
Example: Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
As for the second part of your question:
var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.
Function Declaration
function foo() { ... }
Because of function hoisting, the function declared this way can be called both after and before the definition.
Function Expression
Named Function Expression
var foo = function bar() { ... }
Anonymous Function Expression
var foo = function() { ... }
foo() can be called only after creation.
Immediately-Invoked Function Expression (IIFE)
(function() { ... }());
Conclusion
Douglas Crockford recommends to use function expression in his «JavaScript: The Good Parts» book because it makes it clear that foo is a variable containing a function value.
Well, personally, I prefer to use Declaration unless there is a reason for Expression.
Regarding 3rd definition:
var foo = function foo() { return 5; }
Heres an example which shows how to use possibility of recursive call:
a = function b(i) {
if (i>10) {
return i;
}
else {
return b(++i);
}
}
console.log(a(5)); // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15
Edit:
more interesting example with closures:
a = function(c) {
return function b(i){
if (i>c) {
return i;
}
return b(++i);
}
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8
The first statement depends on the context in which it is declared.
If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program.
If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()"
EDIT:
I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code.
END EDIT
Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore
var foo = function foo() { return 5; }
Is the same as
var foo = function fooYou() { return 5; }
Though the complete difference is more complicated, the only difference that concerns me is when the machine creates the function object. Which in the case of declarations is before any statement is executed but after a statement body is invoked (be that the global code body or a sub-function's), and in the case of expressions is when the statement it is in gets executed. Other than that for all intents and purposes browsers treat them the same.
To help you understand, take a look at this performance test which busted an assumption I had made of internally declared functions not needing to be re-created by the machine when the outer function is invoked. Kind of a shame too as I liked writing code that way.
This question already has answers here:
Closed 14 years ago.
As the title says, whats the difference between
MyFunction = function() {
}
and
function MyFunction() {
}
Nothing?
Duplicate: var functionName = function() {} vs function functionName() {}
The first form is actually a variable with an anonymous function assigned to it, the second is a declared function.
They're almost interchangeable, but have some differences: debuggers have a harder time with anons (because they lack a name) and the JS engine can directly access declared functions wherever they exist in the script, but anons can't be accessed until they have been assigned.
I think you mean
var MyFunction = function() {
}
And in many cases, there is little difference.
The var syntax is sometimes useful when you are inside some sort of wrapping class and want to be sure of your namespace (like in greasemonkey).
Also, I believe the function-are-constructors stuff (with .prototype, etc) do not work with the var syntax.
here is one difference:
function Moose() {
alert(arguments.callee.name); // "Moose"
}
var Cow = function() {
alert(arguments.callee.name); // ""
}
function myFunction(){} is the same as var myFunction = function myFunction(){}. If you just do MyFunction = function(){}, it's like MyFunction = function anonymous(){}.
The variables and functions have different scopes but the function can only be referenced outside the function via the variable name, which needs to be bound to the function.
function myFunction(){} binds the myFunction variable to a function that just happens to have the same name.
There's one subtle difference on Firefox, when you're declaring a window load event handler. Declaring the following in a script tag only works on Firefox:
function onload() {
alert(42);
}
You have to do it like this for IE, Opera, Safari or Chrome:
onload = function () {
alert(42);
}