Why are anonymous functions treated differently from named functions here? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Javascript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?
Today I stumbled upon the following phenomenon:
foo();
bar();
function foo()
{
console.log("inside foo");
}
var bar = function()
{
console.log("inside bar");
}
FireBug complains with the following error message:
bar is not a function
Several tutorials claim that function f() and var f = function() are basically the same thing. Evidently, they are not, but what exactly is going on here?

Function declarations are available anywhere in the scope they're defined in, even before their physical definitions.
var bar = function() { ... }; is a normal variable that happens to hold a function. Like all other variables, it can only be used after its assigned.
(You cannot observe the future value of a variable)

Related

Don't understand how Closure Functions are working? [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 6 years ago.
I am reading eloquentjavascript to learn javascript but this closure thing is confusing me. warp1 is not function but it looks like function and it looks like taking argument too. How do closure functions work ? and what are the reasons we can use it ?
function wrapValue(n) {
var localVariable = n;
return function() { return localVariable; };
}
var wrap1 = wrapValue(1);
var wrap2 = wrapValue(2);
console.log(wrap1());
// → 1
console.log(wrap2());
// → 2
The outer function (wrapValue) returns a function. So the returned function gets assigned to your variables wrap1 and wrap2. That's why you can call the returned function from your variable.
Maybe it's easier to understand when we look at the following.
You can create a function like you did:
function foo() { return "foo"; }
Or you can assign a function to a variable:
var foo = function() { return "foo"; }
The second example basically does exactly the same as your closure does - it assigns a function to a variable.
In all cases, you can call the function with
foo();
Either by variable, or function name.

javascript function declarations and differences in scope [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
Closed 8 years ago.
I couldnT find an answer easily, so even if this question is a dupe, the answers donT come up using these keywords.
I want to know the difference between the different way of declaring functions in a sample app.js
var foo = function()
{
//..
}
function bar()
{
//..
}
var baz= function()
{
//..
}
function qux()
{
//..
}
// other??
I m also not clear about the scope where I can use each function. Thanks!
There are four ways to create a function in JavaScript.
Function declaration
This will create a variable foo in the current scope and assign a named function to it.
function foo () {
}
Function declarations are hoisted so it doesn't matter where, in the applicable scope, you put them. It is considered good coding practise to define them before you use them though.
Anonymous function expression
This will create a function without a name and use it in an expression. In this example it is assigned to the variable something.
something = function () {
};
Named function expression
This is the same as an anonymous function expression except that it has a name, creates a variable of that name in the scope of itself and is horribly broken in older versions of Internet Explorer.
something = function foo () {
};
Function constructor
Do not use function constructors. They are eval by another name. You can read about them on MDN if you're interested.

Named function expression [duplicate]

This question already has answers here:
Why JavaScript function declaration (and expression)?
(5 answers)
Closed 8 years ago.
I'm assigning a named function expression to a property of an object:
var foo = {};
foo.bar = function bar(){
console.log('bar');
};
foo.bar() => bar
bar() => ReferenceError: bar is not defined
Why can't I call bar() directly, why isn't it defined?
I know that I can simply chain the assignment like var bar = foo.bar = function(){}, so I'm not looking for a work-around or other solution, I'm only interested in why it doesn't work.
I've tested in Chrome console and Node.JS.
Named function expressions are simply not supposed to work that way. The function name is only visible inside the function, not outside.
A function instantiation expression that happens to have a name is not the same thing as a function declaration statement. Those are two distinct syntactic (and semantic) entities in the language.

What is the point of using a named function expression? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Why use named function expressions?
(5 answers)
Closed 9 years ago.
I'm going through this blog about the difference between function declarations and function expressions.
It gives these two examples. They call the first an "anonymous function expression" and the second a "named function expression."
// anonymous function expression
var a = function(){
return 3;
}
// named function expression
var b = function bar(){
return 3;
}
I tested these two in Chrome's JS console and I see the following:
a()
=> 3
b()
=> 3
bar()
=> bar is not defined
My question is: In the second function expression declaration, what is the point of "bar"? In general, why does one ever use a named function expression?
Some people prefer to do it like this because if errors occur, your functions have names. It's mostly a matter of preference and how often you have trouble with unnamed functions.
You don't normally see it used in a var declaration, but instead when declaring callbacks:
callbackFunction(function success() { ... }, function fail() { ... })
That way you know which argument is which, they're labelled, and if one of them fails you get a precise indication of which one broke.
var b = function bar(){
return 3;
}
bar()
=> bar is not defined
The identifier bar is only available inside of the function. Try
var b = function bar() {
console.log(bar);
}
b();
why does one ever use a named function expression?
To allow referencing a function expression that was not assigned to a reachable or constant variable, e.g. for recursion in an IEFE.
Also, named functions show up different during debugging, e.g. in call stack (trace)s or breakpoint listings. Often you can use a (named) function declaration instead of a function expression, see also http://blog.niftysnippets.org/2010/03/anonymouses-anonymous.html.

Beginner Javascript: What's the difference between 'function xyz(){}' and 'var xyz = function(){}'? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
I've been going through CodeAcademy's Javascript courses, and a few things have gone over my head. I understand how function work, and I'm trying to wrap my head around OOP and objects/methods.
My question is, what's the difference between creating a function like this:
function countTo(number){
for (var i=1; i<=number; i++){
console.log(i);
}
}
countTo(15);
and creating a function like this:
var countToTwo = function(number){
for (var i=1; i<=number; i++){
console.log(i);
}
};
countToTwo(27);
Both do the same thing and have the same output. Are they exactly the same/interchangeable? Does it matter which one I use when creating a function?
The first one is a function declaration, and is "hoisted", meaning it's immediately available anywhere in the context.
The second one is a function expression, and is treated just like any other variable declaration/assignment. The declaration of countToTwo is hoisted and immediately available anywhere in the scope in which it's declared, but the assignment stays in exactly the same place.
The short of it is that you're not able to call a function declared as an expression until the expression has been parsed.
This code should illustrate a little more clearly.
foo();
//blah();
function foo(){
alert('hoisted and works');
}
var blah = function(){
// not hoisted, would fail if called
}
​
Live Demo

Categories

Resources