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

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.

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.

Confusion regarding Functions as Values concept in javascript [duplicate]

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

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;

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.

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