Home » JavaScript Tutorial

Difference between var and let in JavaScript?

JavaScript var vs let: In this tutorial, we are going to learn about the differences between var and let in JavaScript.
Submitted by Siddhant Verma, on November 23, 2019

You can define your variables in JavaScript using two keywords - the let keyword and the var keyword. The var keyword is the oldest way of defining and declaring variables in JavaScript whereas the let is fairly new and was introduced by ES15.

In this article, we'll look at the differences between the two so you know when to use which for your variables.

Open the chrome dev console to try out the examples by right-clicking on the browser → selecting inspect → selecting console or simply type f12.

Example 1:

var size=32;
console.log(size);

Output

32

Example 2:

var size=63;
console.log(size);

Output

63

We declared a variable size with a value 32. Then we redeclared it with another value, 63. Everything looks fine till now.

let length=14;
console.log(length);

Output

14
let length=14;

let length=20; //will produce error
console.log(length);

Output

Uncaught SyntaxError: Identifier 'length' has already been declared
    at <anonymous>:1:1
let length=14;

length=20; //no produce error
console.log(length);

Output

20

Now we create a length variable with a value 14 but this time using the let keyword. When we redeclare the same variable with another value we get a SyntaxError saying it has already been declared. The first point of difference between let and var is that using var we can redeclare those variables but with let, we can only redefine them, not redeclare them. When we reassign the value 20 to the variable length, we get no error on the console and our length variable happily takes a new value.

var ironMan = 'red';
var captainAmerica = 'blue';
if (ironMan === 'red') {
    var ironMan = 'silver';
    let captainAmerica = 'golden';
    console.log(ironMan);
    console.log(captainAmerica);
}

Output

silver
Golden
var ironMan = 'red';
var captainAmerica = 'blue';
if (ironMan === 'red') {
    var ironMan = 'silver';
    let captainAmerica = 'golden';
    console.log(ironMan);
    console.log(captainAmerica);
}

Output

silver
Blue

The next difference between the two is the scope. You can observe from the above code that captainAmerica is declared again inside using the let keyword with a value 'golden' and inside that if block it persists that value, however, outside that if block when we log it's value to the console we get the older value 'blue' which was defined outside the if block. Thus variables declared using the let keyword have block scope. On the other hand, we changed the value of ironMan inside the if block and it continues to hold that value even after the if block is over. We can say that var takes the scope of it's enclosing execution context which can be a function or even the global scope as in this case.

Heads up: The reason let was introduced was to avoid using global variables and namespaces everywhere. It's a bad, no wait, terrible programming habit. Avoid using global variables where their global scope renders absurd. Use let wherever possible.

Finally, the last difference I want to talk about is Hoisting. Consider the following piece of code,

x = 5;
console.log(x);
var x;

Output

5

If you've worked with languages like C/C++ you might find it strange. In such languages, you can expect an error saying something like x is not defined because compiler reads from top to bottom. So is JS also executed from top to bottom? Well, if it were, you wouldn't be able to do this. Then how come we can use a variable and declare it later? The answer is hoisting. Hoisting means moving all declarations to the top. This means that while executing the code, all variable declarations are on the top so till the time you come to x=5 line you already know that x has been declared a variable somewhere in the program.

y = 3;

function setRandom(y) {
    console.log('Before declaring y: ', y);
}
setRandom();
var y;
console.log('After declaring y: ', y);

Output

Before declaring y:  undefined
After declaring y:  3

Let's try to hoist a variable using let,

x = 5;
console.log(x);
let x;

Output

VM2466:1 Uncaught ReferenceError: Cannot access 'x' before initialization
    at <anonymous>:1:2

We get an error saying we can't access it before it is even initialized. So are variables declared with the let keyword not hoisted? They are, but they're hoisted in a temporal dead zone. A zone where you can use variables that have not been defined yet.

Note: if you are using strict mode in your JavaScript then you're more likely to run into getting undefined values for such types of code because strict mode does not allow any hoisting to take place.

So is hoisting in TDZ useless? Well not really, consider the following example using an asynchronous function.

for (var i = 0; i < 3; i++) {
    setTimeout(function() {
        console.log(i);
    }, 1000)
}

Output

3

Out setTimeout is an asynchronous function and after 1 sec it prints the value of i which was incremented 4 times while that asynchronous function was running. However if we use let instead of var,

for (let i = 0; i < 3; i++) {
    setTimeout(function() {
        console.log(i);
    }, 1000)
}

Output

0
1
2

Now we get all the values that i took during that loop traversal. This is because of the TDZ or the temporal dead zone where let is hoisted. Thus using async can help you retain your values through TDZ hoisting if you use let instead of var. Remember to clean your code by replacing all var with let and make it a good practice to use block scopes instead of global scopes!






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.