Confusion regarding Functions as Values concept in javascript [duplicate] - javascript

This question already has answers here:
Javascript named function as an expression
(1 answer)
Javascript functions like "var foo = function bar() ..."?
(9 answers)
Closed 3 years ago.
when we declare a named function let's say in google chrome console and if we call it then the contents of the function are getting executed. how ever if we create a reference for that function and if I am trying to call that function with which it is named, I am getting ReferenceError.
function foo() {
console.log("something");
}
foo(); // will print out "something"
var x = function bar() {
console.log("something x");
}
x(); //will print "something x"
bar(); //throws ReferenceError, bar is not defined.

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();

Related

Different behaviors between the same var name and function name VS two same function name [duplicate]

This question already has answers here:
Javascript - Precedence in hoisting
(2 answers)
Closed 5 months ago.
Recently, I received this interview question, I know it's weird to declare var name and function name the same, but the code runs without errors, and I don't know how to explain this behavior, hence the question.
In the Chrome console, the following code logs 1:
var foo = function () {
console.log(1)
}
function foo() {
console.log(2)
}
foo()
And the following code logs 2:
function foo() {
console.log(1)
}
function foo() {
console.log(2)
}
foo()
Why are the results not the same?
Function declarations, including the assignment of their values, are hoisted. Variable assignments are not.
In the first case, the function declaration for foo is hoisted so is overwritten by the variable assignment even though that appears earlier in the source order.

unexpected results with function and variable hoisting [duplicate]

This question already has answers here:
Function declarations precedence/overwriting variable declarations? Hoisting? Why?
(2 answers)
JavaScript hoisting for multiple declarations of the same variable
(1 answer)
Order of hoisting in JavaScript
(2 answers)
Closed 4 years ago.
I'm reading the second book of the series "You don't know JS" and I've read that functions are hoisted before variables.
So this is the code:
foo(); // 1
var foo;
function foo() {
console.log( 1 );
}
foo = function() {
console.log( 2 );
};
The output of this will be 1. But why? Functions are hoisted first and then variables. So after my function foo (the one that prints 1) is hoisted it has to be followed by the variable foo. So the result should be "undefined" instead of "1".
I expect the code to behave as if it had been:
// hoisted first
function foo() {
console.log( 1 );
}
// hoisted second
var foo; // implicitly initialized to 'undefined'
foo(); // call 'undefined' - error?
foo = function() {
console.log( 2 );
};
What's happening here?
As said, functions are hoisted before variables; if the interpterer comes across var foo after foo has already been defined in the scope, it will simply be ignored. It doesn't assign foo to undefined, it only ensures that a variable named foo exists in the current scope - which it already does.
As it says in your You Don't Know JS link:
multiple/duplicate var declarations are effectively ignored
Here's another commonly seen example of hoisted duplicate variables being ignored that might be more familiar/intuitive:
if (false)
var foo = false;
else
var foo = true;
turns into
var foo;
var foo; // does not actually do anything; does not assign `undefined` to `foo`, ignored
// foo just *happens* to not have anything assigned to it in almost all cases like this
if (false)
foo = false;
else
foo = true;

Javascript - why my example alerts 1 instead of 10? [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 5 years ago.
My sample code:
var foo = 1;
function bar() {
foo = 10;
return;
function foo() {}
}
bar();
alert(foo);
Why does it alert 1? I am expecting 10.
However if I comment out function foo(){} after return, it does return 10.
Function declarations inside other functions are treated as if they appeared at the very start of the containing function. That is, your bar() function is treated as if it looked like:
function bar() {
function foo() {}
foo = 10;
return;
}
Thus foo is a local symbol in the function, and assignment to it does not affect the global foo.

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.

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

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)

Categories

Resources