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.