In this article we are going to show you Difference between let and const and var in JavaScript.
In JavaScript, let, const, and var are used to declare variables. The main differences between them are as follows:
1.var
var was the original way to declare a variable in JavaScript. Variables declared with var are function-scoped, which means that the variable is accessible within the function it was declared in or globally if it was declared outside a function. var variables can be reassigned and also re-declared within the same scope.
Example:
function example() { var a = 1; if (true) { var a = 2; console.log(a); // 2 } console.log(a); // 2 }
2.let
let was introduced in ES6 (ECMAScript 2015) as a way to declare variables with block-scoping. Variables declared with let are only accessible within the block they were declared in, such as inside an if statement or a for loop. let variables can be reassigned, but not re-declared within the same scope.
Example:
function example() { let a = 1; if (true) { let a = 2; console.log(a); // 2 } console.log(a); // 1 }
3.const
const is also introduced in ES6, and it is used to declare variables that cannot be reassigned. Variables declared with const are also block-scoped, which means they are only accessible within the block they were declared in. const variables must be assigned a value at the time of declaration and cannot be re-assigned or re-declared within the same scope.
Example:
function example() { const a = 1; if (true) { const a = 2; console.log(a); // 2 } console.log(a); // 1 }
In summary, let is used when you need to reassign the variable, const is used when you want a variable whose value should not change, and var is used when you need to declare a variable within a function scope or create a global variable.