Js 16
Js 16
Js 16
In the very first chapter about variables, we mentioned three ways of variable
declaration:
let
const
var
let and const behave exactly the same way in terms of Lexical Environments.
But var is a very different beast, that originates from very old times. It�s
generally not used in modern scripts, but still lurks in the old ones.
If you don�t plan on meeting such scripts you may even skip this chapter or
postpone it, but then there�s a chance that it bites you later.
From the first sight, var behaves similar to let. That is, declares a variable:
function sayHi() {
var phrase = "Hello"; // local variable, "var" instead of "let"
alert(phrase); // Hello
}
sayHi();
For instance:
if (true) {
var test = true; // use "var" instead of "let"
}
If we used let test instead of var test, then the variable would only be visible
inside if:
if (true) {
let test = true; // use "let"
}
function sayHi() {
if (true) {
var phrase = "Hello";
}
alert(phrase); // works
}
sayHi();
alert(phrase); // Error: phrase is not defined (Check the Developer Console)
As we can see, var pierces through if, for or other code blocks. That�s because a
long time ago in JavaScript blocks had no Lexical Environments. And var is a
remnant of that.
In other words, var variables are defined from the beginning of the function, no
matter where the definition is (assuming that the definition is not in the nested
function).
So this code:
function sayHi() {
phrase = "Hello";
alert(phrase);
var phrase;
}
sayHi();
�Is technically the same as this (moved var phrase above):
function sayHi() {
var phrase;
phrase = "Hello";
alert(phrase);
}
sayHi();
�Or even as this (remember, code blocks are ignored):
function sayHi() {
phrase = "Hello"; // (*)
if (false) {
var phrase;
}
alert(phrase);
}
sayHi();
People also call such behavior �hoisting� (raising), because all var are �hoisted�
(raised) to the top of the function.
So in the example above, if (false) branch never executes, but that doesn�t matter.
The var inside it is processed in the beginning of the function, so at the moment
of (*) the variable exists.
function sayHi() {
alert(phrase);
sayHi();
The line var phrase = "Hello" has two actions in it: