This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 7 years ago.
In the code below
var x = 1;
(function () {
console.log(x);
var x = 2;
}());
Why is it that when console.log(x), x is undefined?
Variable hoisting. The actual code is executed like this.
var x = 1;
(function() {
var x; // x = undefined
console.log(x);
x = 2;
})();
Edit: On Mr Lister's advice, a bit on variable hoisting. From MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var):
"Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global."
Because of the compiler, even if you initiate a var down below the code, the compiler send it to the top, just like var x;, so it first initiate as undefined "x" before running console.log, that's why is such a good practice to initate all vars you're going to use first thing in the function, so these mistakes won't happen.
Related
This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 1 year ago.
I am learning javascript global variable and local variable. When I did experiment with it (see jsfiddle below) then I am confuse that why after executing myFunction1() the value of variable a became 4 instead of 5. What do you think happened inside the javascript memory which made its value 4 instead of 5 ?
var a = 4;
myFunction1();
function myFunction1() {
a= 5;
var a= 6;
}
alert(a); //a = 4
myFunction2();
function myFunction2() {
a= 5;
}
alert(a); //a = 5
You've just discovered hoisting.
By declaring var a inside the function, it is available to the whole function context (even before its declaration), so when you write a = 5 the actual a is not the one you expect, it's the function-scoped a.
In the second case, a is the one you expect (outside the function)
This question already has answers here:
JavaScript loop variable scope
(5 answers)
How do JavaScript closures work?
(86 answers)
Closed 3 years ago.
My code was compiled to the following, and it works, but I do not know why. The variable that references the incrementing value is not included as an argument in the for loop.
var _loop2 = function _loop2() {
var p = document.createElement('p');
p.setAttribute('class', 'location__result');
p.setAttribute('data-id', response.features[i].id);
p.setAttribute('data-center', response.features[i].center);
p.textContent = response.features[i].place_name;
p.addEventListener('click', function () {
endingInput.value = p.textContent;
endingResults.style.display = "none";
placeIconAndZoom(p, position);
});
endingResults.appendChild(p);
};
for (var i = 0, length = response.features.length; i < length; i++) {
_loop2();
}
A function (x) declared inside another function (y) has access to all variables in the scope of the x (unless they are masked by another variable of the same name).
y can also be the global or module scope rather than a function per se.
var i = "example";
function x() {
console.log(i);
}
x();
This is the classic case of why const and let were introduced in ES6
var has a function level scope. This differs to const and let in terms of scoping, where the variable defined in var can be accessible anywhere in hits function declaration.
In your case, we declare var i inside the for loop (the function level scope), and your for loop is calling your _loop2 function. Since _loop2 is part of the for loops function scope, you're able to access that variable.
This SO answer can explain it a million times better than I can:
What's the difference between using "let" and "var"?
You can fix this by either adding: use 'strict' ontop of your script file, but a much better way is to avoid using var all together (unless there is a special circumstance) and switch it to let
This question already has answers here:
Why does shadowed variable evaluate to undefined when defined in outside scope?
(6 answers)
Closed 3 years ago.
Why is the x variable in the example below returning undefined rather than 25?
var x = 25;
(function() {
console.log(x);
var x = 10;
})();
This is common problem of hoisting in javascript.The code actually looks like this.The value is assigned after the console.log.
The second undefined(if run on developer's tool) is because the function is not explicitly returning anything
This is how Javascript actually executes your code due to var hoisting:
var x = 25;
(function() {
var x;
console.log(x);
x = 10;
})();
It's Self-Invoking Functions that will invoke without calling from specific function or place. and your declared x inside that function and preparing for running that function make javascript ignore global variable x and try to create local x.if you remove var x = 10; from the function inside then everything will be OK:
var x = 25;
(function() {
console.log(x);
})();
This question already has answers here:
javascript variable scope in the IF statement
(5 answers)
Closed 6 years ago.
I am currently reading through some javascript tutorials and I came upon this bit of example code from here: http://www.w3schools.com/js/js_if_else.asp
if (hour < 18) {
greeting = "Good day";
}
In this example, the greeting variable is not prefixed with a var statement. Now I looked up what this means, and my understanding is that it causes java script to look to a higher scope, if no variable is discovered by the global scope it creates it.
So is this tutorial doing this because the if statement's block is a local environment? If so does that mean that if I were to have some code that looked like this:
if (condition){var x=10};
else {var x=5};
then there would still be no global variable x for me to call?
In JavaScript (ES5), an if statement does not create a local scope when declaring with var. Local scope is created with a function.
W3Schools is notorious for using bad practices in their code samples, and you've found one example of this. They are creating a globally-scoped variable.
Blocks will only create a local scope for variables declared with the new let keyword. If you're using an older version of JavaScript, or if you're using the var keyword, then the variable is scoped to the innermost function that the variable is declared in.
Variables declared via var outside of any function are scoped to the window (global) scope.
{
var x = "hello world";
}
document.getElementById("var-value").innerHTML = x;
<span id="var-value"></span>
In the above snippet, if you replaced var with let, it would produce an error because x is undefined.
{
let x = "hello world";
}
document.getElementById("var-value").innerHTML = x;
<span id="var-value"></span>
You would be able to get the value of x outside of the if..else. This is due to JavaScript having function scope rather than block. I created a JSFiddle of your example, which can be found at https://jsfiddle.net/h4gjb8mt/
Example:
var condition = true;
if (condition) {
var x=10;
}
else {
var x=5;
}
console.log(x);
This question already has answers here:
Global JavaScript Variable Scope: Why doesn't this work?
(5 answers)
Javascript function scoping and hoisting
(18 answers)
Closed 8 years ago.
I need to understand how the JavaScript engines in browsers read functions. Consider the code below:
var g = 5;
alert(g); //alerts 5
function haha() {
alert(g); // alerts NOTHING. Why is this? Why not alert 5? var g = 45 hasn't yet occurred
var g = 45;
alert(g); // alerts 45
};
haha();
alert(g); // alerts 5. Because g = 45 is a local variable.
Fiddle
The effect you're seeing where alert(g) in the haha function alerts undefined is from variable hoisting.
The haha function is actually executed as:
function haha() {
var g;
alert(g);
g = 45;
alert(g);
}
This is because variable and function definitions are hoisted to the top of their scope in JavaScript.
The effect can lead to some rather unintuitive behavior, such as what you're seeing. The simple solution is to always declare your variables and functions before any executing code so that the written code matches what's being executed.