This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 5 years ago.
I have small function logically output should be 1 but i am getting 10 .. Can any one help me out with this logic.
var a=1;
function foo() {
if(!a){
var a=10;
}
console.log(a);
}
foo();
Output is coming 10 not 1 . how.
It's because of something called "hoisting".
https://www.w3schools.com/js/js_hoisting.asp
JS interpret your code like this
var a=1;
function foo(){
var a;
if(!a){
a=10;
}
console.log(a);
}
foo();
In addition to hoisting as mentioned in other answers, keep in mind that when writing ES6 (by using let or const) your code will behave as you expect it to.
Why does this happen? Because let and const have block-level scoping and not function-level scoping.
let a = 1;
function foo() {
if (!a) {
let a = 10;
}
console.log(a);
}
foo();
This is why, when you use a JavaScript linting mechanism, like ESLint, you will see rules like vars-on-top ( https://eslint.org/docs/rules/vars-on-top ) specifically to avoid these types of issues.
Related
This question already has an answer here:
Why JavaScript function declaration behave differently in chrome and safari? [duplicate]
(1 answer)
Closed 5 years ago.
In a book You Don't Know JS: Scope & Closures There is this sample of code I don't understand fully.
"Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this code implies:"
foo(); // "b"
var a = true;
if (a) {
function foo() { console.log( "a" ); }
}
else {
function foo() { console.log( "b" ); }
}
What does it mean? How is it even possible? Is the conditional not working?
It's happening because function declarations are moved to the top of the file by the javascript parser. That's what they mean by hoisting. The last declaration of foo overwrites the first when they are hoisted.
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.
This question already has answers here:
What are the precise semantics of block-level functions in ES6?
(2 answers)
Closed 6 years ago.
I read Kyle's I don't know JS and came to know that function declarations will hoist first before the var. So in the below code
<script>
foo();
var a = true;
if ( a ) {
function foo() { console.log( "a" ); }
}else {
function foo() { console.log( "b" ); }
}
foo();
</script>
foo should be hoisted first and should print "b" as output for the first foo(), right? or am I missing anything?
Explanation or a link to understand to the code and hoisting in different scenario's would be a great help.
Hoisting (in the way that you're expecting here) will only work when there is a precedential order of things that is unambiguous. In this case, because your function is defined inside an if block, hoisting it will not happen as you expect it to.
This will work:
foo();
var a = true;
function foo() { console.log( "a" ); }
foo();
Because it removes from the equation your if statement.
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
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)