JavaScript
Variable by definition is how you store values which can be changed later on.
 
When dealing with variables in JavaScript you must have heard about the keyword var which was used extensively (as it was the only way to declare a variable in JavaScript before ES6) and in latest versions we have got the option of let and const .
 
 

Scopes of var and let/const

 
When a variable is declared using var keyword, it becomes a function scoped variable, meaning irrespective of the blocks it can be used anywhere in the function ( you will understand the blocks thing in a while now). So let say you declare a variable using var keyword inside a for loop which is inside a function, in regular circumstances once the for loop ends the variable will no longer be accessible but as you have declared a variable using var keyword it will be accessible.
 
function sayHello() {
    for (var i = 0; i < 5; i++) {
        console.log("Inside the for: ", i);
    }

    console.log("After the for loop: ", i);
}

sayHello();

 

Not only that the variables declared using var keyword can also be re-declared and it doesn't cause any errors. 

var name = 'CodeWithZ';
var name = "Test";

var counter = 5;

if (counter > 4) {
    var name = "CodeWithZ Inc";
}

console.log(name);

 This code block will give you an output of CodeWithZ Inc

Let and const

Then with ES6 enters let and const keywords which resolves the above issues and make the JavaScript variables act normally.
 
let and const both are block scoped and not function scoped, so unlike above scenario once a variable is defined we won't be able to use it outside the block as you can see in the code block below.
 
function sayHi() {
    for (let i = 0; i < 5; i++) {
        console.log("Inside the for: ", i);
    }

    console.log("After the for loop: ", i);
}

sayHi();
 
As we are using a let variable after the scope it will result in an error.
 

 

One more visible difference in let and const vs var is that, variable once declared using let or const cannot be re-declared in the same block. Any attempt to do same will result in an error.
 
One more visible difference in let and const vs var is that, variable once declared using let or const cannot be re-declared in the same block. Any attempt to do same will result in an error.
 
And one of the major difference between let and const is
 
Variable declared using let is allowed to change its value whereas variable declared using const cannot change the value which is originally assigned to it.
 
const someValue = "Test Value";

someValue = "Hello";
 
 

 

Following table will help you understand the difference between let and const vs var.

 

 

Related Posts

Table Of Contents

;