In JavaScript variables were declared using the var keyword up until ECMAScript 6 (ES6). Before ES6, we used to declare variable using the var keyword where variables had global scope by default or in other words we can say the variables declared using the var keyword are available throughout the program and not just within a block.
While on the other hand, if we want a variable to exist only within a block we can use the let keyword.
Now let's see a few differences between variables declared using the keywords var and let.
Global window object
When we declare a variable using the var keyword, it is added to the global window object and can be accessed using the same whereas when we declare a variable using the let keyword it is not added to the global window object. Let's take an example and see,
var one = "Hello";
let two = "World";
console.log(window.one); \\ Hello is printed in console
console.log(window.two); \\ undefined
As only global variables, which can be accessed throughout the program gets added to the global window object and as variables declared using the let keyword have block scope they are not added to the global window object.
Scope of Variable
As mentioned already, variables declared using the let keyword have a block scope i.e. they are available only within the code block where it is declared or initialised whereas variables declared using the var keyword have a program scope i.e. it is available throughout the program.
Let's take an example,
for(let i=0; i<5; i++)
{
console.log(i); // 0 1 2 3 4
}
console.log(i); // undefined as 'i' is not available outside the foor loop block
In the code snippet above you can see how scope of variable declared using let keyword works.
for(var i=0; i<5; i++)
{
console.log(i); // 0 1 2 3 4
}
console.log(i); // 5 is printed in console
You will see many trick coding interview questions based on scope of variables now during JavaScript interviews. When used inside a function, both the variables types will be avialble within the scope of the function.
Redeclaration of Variables
When we declare a variable, we also provide value for it, which can obviously be changed. But not anymore, when we declare a variable using the let keyword we cannot change it's value once defined.
The error can be seen when we are working in 'strict mode'.
First, let's take an example with var keyword,
'use strict'
var one = "I am number 1"; // declared
var one = "I am the new number 1"; // redeclared easily
But this is not the case with let keyword,
'use strict'
let two = "I am number 2"; // declared
let two = "I am new number 2"; // SyntaxError: two is already declared
Conclusion
So these are some differences between let and var keyword, used for variable declaration in JavaScript. The overall conclusion is, to justify scopes of variables you must use let instead of var for defining variables. And avoid using var keyword unless you need a global variable.
You may also like: