Does an if statement create a local scope? [duplicate] - javascript

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

Related

Javascript - Defining a local variable after assigning a new value in a already declared global variable is overriding the global variable. Why? [duplicate]

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)

Why does this for loop work without passing the incrementing variable? [duplicate]

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

Javascript lambda function does not see variable from parent scope [duplicate]

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.

Value of a global variable redeclared in the scope of a function [duplicate]

This question already has answers here:
Why is my global variable shadowed before the local declaration?
(3 answers)
Closed 4 years ago.
My question might be a little "schoolish" but i fell upon that block of code and i realized i didn't understand why it returned "undefined". By using the Chrome debugger, i noticed the a variable seems to become undefined the moment we enter the function. My first feeling was that block of code would return 2.
If anyone can put some light on this example, that would be much appreciated
var a = 2;
console.log((function(condition){
if (condition) {
var a = 4;
return a;
} else {
return a;
}
})(false))
In case the title of this question is not clear enough, i let you suggest something else more appropriate.
A var declaration is always interpreted as if it were written at the top of the function body, so your code is run as
var a = 2;
console.log((function(condition){
var a;
if (condition) {
a = 4;
return a;
} else {
return a;
}
})(false))
Since condition is false, the else clause runs and the function returns the uninitialized value of a. The local var declaration hides the relatively global a declared outside the function; it plays no part in the way the function behaves.
If you had declared the local a with let instead of var, things would be different. The a reference in the else clause would have referred to the more global a. A let declaration is scoped to it's enclosing block statement, unlike var which always makes function-scoped variables.

Difference between declaring variable [duplicate]

This question already has answers here:
Is using 'var' to declare variables optional? [duplicate]
(14 answers)
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 7 years ago.
what is the difference between the way a variable can be declared?
a = 5;
and
var a = 5;
Is there any relation with scoping also?
var a will create local variable. The other will create and/or set a global variable.
Most of the time, you are better off creating local variables, unless you absolutely need to create a global variable.
a = 5 will declare a global variable from any scope. var a = 5 will declare a variable within the declared scope.
a = 5; //global variable
var b = 6; // global variable
function foo(){
var c = 7; //local variable
d = 9; //global variable
}
One declares a variable, the other one doesn't.
The var keyword is for declaring variables, and the variable is created in the current scope.
If you assign a value to a variable that doesn't exist yet, the variable is implicitly created in the global scope.
a = 5;
This will set a variable, if the variable has not already been declared then it will be created in the global scope (which you probably don't want).
var a = 5;
This will create and set a variable. The variable will be created as a local variable in the function scope if inside a function, otherwise will create it globally.
Also worth noting that the statement var a = 5 will be hoisted to the top of your function. I.e.
function() {
doSomestuff();
a = 4;
var a = 5;
doOtherStuff();
}
actually becomes
function() {
var a = 5;
doSomestuff();
a = 4;
doOtherStuff();
}
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var for more info.
Also worth noting that if you use strict mode you cannot declare a variable with just a = 5. You must use the var keyword.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
This is worth doing because turns your undetectable mistakes into obvious errors.

Categories

Resources