1

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?

A-P
  • 497
  • 1
  • 4
  • 9

3 Answers3

2

In JavaScript (ES5), an if statement does not create a local scope when declaring with var. Local scope is created with a function.

carmouche
  • 159
  • 1
  • 1
  • 7
1

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>
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
0

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);
LukeGeneva
  • 584
  • 1
  • 3
  • 15