Till now in this course we have been using
let keyword to declare variables.
let was added in ES6(ECMAScript 2015). Earlier
var keyword was used to declare variables. In many tutorials, articles you will find the usage of
var if they are written before ES6 was released.
var are used to declare variables, usage of
var is discouraged while that of
let is recommended. This is because variables declared with
var can be problematic in a couple of situations and this section will discuss them.
Variable scope in function
In most programming languages, a variable declared inside a block in a function is scoped to that block. That is, a variable declared inside a loop block or an
if block will not be accessible outside these blocks.
let behaves in the same way but if a variable is declared with
var, then it will be available inside the entire function body(even outside the block in which it is declared). Example,
In above code, a function is defined which contains a loop with a loop variable i declared using
let. The loop also declares another variable lang inside an
if block using
var keyword. After the loop ends, both the variables are printed to the console and below is the output produced.
Uncaught ReferenceError: i is not defined
at demo (<anonymous>:6:13)
It is clear from the output that the variable declared inside the
if blocks using
var is accessible outside the loop also while the variable declared with
let is not.
This becomes confusing for learners and developers since most programming languages do not behave in the same way. Variables declared inside a block in most languages are scoped to that block only.
If a variable is declared outside of any block or function with
var, it is attached to the window(or global) object while that declared using
let keyword does not. Example,
// declare a variable with var var car='Audi'; // print it using window object console.log(window.car); // declare a variable with let let laptop='sony'; // print it using window object console.log(window.laptop);
As you can see, the variable created with
let is not accessible using
window object while that created with var is. This becomes a big problem if a variable with the same name is also declared in some other library used in an application.
Since the variable declared with
var becomes a global variable, it can be easily overwritten by the external library making your code to behave unexpectedly and it will be very hard to debug the cause.
let to declare variables and not