JavaScript Functions Like "Var Foo = Function Bar() ..."

Javascript functions like var foo = function bar() ...?

You are seeing a named function expression (NFE).

An anonymous function expression is where you assign a function without a name to a variable1:

var add = function () {
console.log("I have no own name.");
}

A named function expression is where you assign a named function to a variable (surprise!):

var add = function addNums() {
console.log("My name is addNums, but only I will know.");
}

The function's name is only available within the function itself. This enables you to use recursion without necessarily knowing the "outside name" of the function - even without having to set one in the first place (think callback functions).

The name you choose shadows an existing name, so if another addNums is defined elsewhere it will not be overridden. This means you can use any name you like without fear for scoping problems or breaking anything.

In the past you would have used arguments.callee to refer to a function inside itself without knowing its name. But support for that is being removed from JavaScript2, so NFEs are the correct way to do this nowadays.

Here is a lot of stuff to read on the topic: http://kangax.github.io/nfe/


1 Assigning it to a variable is not necessary, it just serves as an example to distinguish it from a plain function declaration. It could be any other context where JS expects an expression (a function argument, for example).

2 You will receive an error if you have strict mode in effect and try to use arguments.callee.

Named Function Expression : Difference between var bar = function () {} & var bar = function foo(){}

Method a: a variable named bar that refers to the anonymous function. function can only be used by using the variable bar wherever it is in scope.

Method b: a variable name bar that refers to a named function foo. foo can still be used by name anywhere it is in scope along with using bar as well.

As Paulpro mentioned - foo is only in scope inside the function itself, nice for recursive functions.

What is the difference between function foo(){} and foo: function(){} in Javascript?

You can write function in two ways: as named function or as variable that has value as anonymous function:

var fooBoo = function () {};
function fooBoo(){}

Calling it is the same: fooBoo().


From your example it seems that you have object with one of keys with function:

var myObj = {
fooBar: function () {}
}

Now in this situation you can't replace it with function fooBar(){} as it would end up in wrong syntax:

// NOT VALID!
var myObj = {
function fooBar() {}
}

Confusion regarding Functions as Values concept in javascript

In the above code function bar(){...} when assigned to a variable x acts as function expression not function declaration .The function bar becomes local variable to x. According to MDN

a name can be provided with a function expression and can be used inside the function to refer to itself,

var x = function bar() { console.log(bar) console.log("something x");}x();

whats the difference between function foo(){} and foo = function(){}?

No, they're not the same, although they do both result in a function you can call via the symbol foo. One is a function declaration, the other is a function expression. They are evaluated at different times, have different effects on the scope in which they're defined, and are legal in different places.

Quoting my answer to this other question here (edited a bit for relevance), in case the other question were ever removed for some reason (and to save people following the link):


JavaScript has two different but related things: Function declarations, and function expressions. There are marked differences between them:

This is a function declaration:

function foo() {
// ...
}

Function declarations are evaluated upon entry into the enclosing scope, before any step-by-step code is executed. The function's name (foo) is added to the enclosing scope (technically, the variable object for the execution context the function is defined in).

This is a function expression (specifically, an anonymous one, like your quoted code):

var foo = function() {
// ...
};

Function expressions are evaluated as part of the step-by-step code, at the point where they appear (just like any other expression). That one creates a function with no name, which it assigns to the foo variable.

Function expressions can also be named rather than anonymous. A named one looks like this:

var x = function foo() {  // Valid, but don't do it; see details below 
// ...
};

A named function expression should be valid, according to the spec. It should create a function with the name foo, but not put foo in the enclosing scope, and then assign that function to the x variable (all of this happening when the expression is encountered in the step-by-step code). When I say it shouldn't put foo in the enclosing scope, I mean exactly that:

var x = function foo() {
alert(typeof foo); // alerts "function" (in compliant implementations)
};
alert(typeof foo); // alerts "undefined" (in compliant implementations)

Note how that's different from the way function declarations work (where the function's name is added to the enclosing scope).

Named function expressions work on compliant implementations, but there used to be several bugs in implementations in the wild, most especially Internet Explorer 8 and earlier (and some early versions of Safari). IE8 processes a named function expresssion twice: First as a function declaration (upon entry into the execution context), and then later as a function expression, generating two distinct functions in the process. (Really.)

More here: Double take and here: Named function expressions demystified


NOTE: The below was written in 2011. In 2015, function declarations in control blocks were added to the language as part of ECMAScript 2015. Their semantics vary depending on whether you're in strict or loose mode, and in loose mode if the environment is a web browser. And of course, on whether the environment you're using has correct support for the ES2015 definition for them. (To my surprise, as of this writing in July 2017, Babel doesn't correctly transpile them, either.) Consequently, you can only reliably use function declarations within control-flow structures in specific situations, so it's still probably best, for now, to use function expressions instead.


And finally, another difference between them is where they're legal. A function expression can appear anywhere an expression can appear (which is virtually anywhere). A function declaration can only appear at the top level of its enclosing scope, outside of any control-flow statements. So for instance, this is valid:

function bar(x) {
var foo;

if (x) {
foo = function() { // Function expression...
// Do X
};
}
else {
foo = function() { // ...and therefore legal
// Do Y
};
}
foo();
}

...but this is not, and does not do what it looks like it does on most implementations:

function bar(x) {

if (x) {
function foo() { // Function declaration -- INVALID
// Do X
}
}
else {
function foo() { // INVALID
// Do Y
}
}
foo();
}

And it makes perfect sense: Since the foo function declarations are evaluated upon entry into the bar function, before any step-by-step code is executed, the interpreter has no idea which foo to evaluate. This isn't a problem for expressions since they're done during the control-flow.

Since the syntax is invalid, implementations are free to do what they want. I've never met one that did what I would have expected, which is to throw a syntax error and fail. Instead, nearly all of them just ignore the control flow statements and do what they should do if there are two foo function declarations at the top level (which is use the second one; that's in the spec). So only the second foo is used. Firefox's SpiderMonkey is the standout, it seems to (effectively) convert them into expressions, and so which it uses depends on the value of x. Live example.

In const a = b = b([ { var: foo }, { var: baz } ]); is b a function, array, or variable?

Functions in JavaScript are first-class citizens. This means that you can treat a function just like any other variable. This allows you to do things such as assigning them to other variables etc...:

const foo = arg => arg;const also_foo = foo;
console.log(also_foo("hello"));

var functionName = function() {} vs function functionName() {}

The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).

For example, a function expression:

// TypeError: functionOne is not a functionfunctionOne();
var functionOne = function() { console.log("Hello!");};

If functions in JS are first-class, what allows them to be called before they are defined?

Because you don't compare the same thing. In your example - you compare function declaration function foo()... with variable declaration and assignment in var foo = 'bar';

A more correct comparison would be of:

console.log(foo);
var foo = 'bar';

with

console.log(foo());
var foo = function() {
return 'bar';
}

The functional declaration is interpreted differently due to the way hoisting works. Hoisting moves all declarations to the top of the closest scope, while leaving assignments in their place.

Function declaration is special in that sense, since it's both declaration and expression/assignment in one statement and thus hoisted together.

As an example: you can look at expressions like:

console.log(foo);
var foo = 'bar';

as this:

var foo;
console.log(foo); //prints undefined
foo = 'bar';

and

console.log(foo());
var foo = function() {
return 'bar';
}

as this:

var foo;
console.log(foo());
foo = function() {
return 'bar';
}


Related Topics



Leave a reply



Submit