var, let, and const are all used to declare variables in JavaScript, but they differ in their scope, hoisting, and assignability.
varis used for variable declaration in pre-ES6 JavaScript. It has function scope, meaning that if it is declared inside a function, it is only accessible within that function. Variables declared withvarcan be hoisted, which means that they can be used before they are declared in the code.varvariables can also be reassigned.
Example:
function example() {
var x = 1;
if (true) {
var x = 2;
console.log(x); // Output: 2
}
console.log(x); // Output: 2
}letandconstare introduced in ES6 (ECMAScript 2015) and have block scope. Block scope means that if a variable is declared inside a block (e.g., inside a loop or an if statement), it is only accessible within that block. Variables declared withletorconstare not hoisted, which means that they cannot be used before they are declared.constvariables cannot be reassigned, whileletvariables can.
Example:
function example() {
let x = 1;
if (true) {
let x = 2;
console.log(x); // Output: 2
}
console.log(x); // Output: 1
}In summary, var has function scope, can be hoisted, and can be reassigned. let and const have block scope, cannot be hoisted, and const cannot be reassigned, while let can be. It is recommended to use let and const instead of var for better code readability and maintainability.
function example() {
const x = 1;
if (true) {
const x = 2;
console.log(x); // Output: 2
}
console.log(x); // Output: 1
}
0 Comments