let, const, and var are used to declare variables, but they have some key differences in terms of hoisting, scope, and mutability.
var has function scope. If a variable is declared inside a function using var, it is only accessible within that function.
If declared outside a function, it has global scope
Variables declared with var can be reassigned.
Variables declared with var are hoisted to the top of their scope. This means that the variable declaration is moved to the top during the compilation phase, but the assignment remains in its original location.
function varDemo() { if (true) { var count = 7; } console.log(count); // 7 (accessible outside the block) } console.log(count); // Error - count is not defined (block-scoped)
let has block scope. Variables declared with let are limited to the block (enclosed by curly braces) in which they are defined.
It is not hoisted outside the block.
Variables declared with let can be reassigned.
function letDemo() { if (true) { let count = 7; } console.log(count); // Error - count is not defined (block-scoped) } console.log(count); // Error - count is not defined (block-scoped)
Variables declared with let are hoisted to the top of their block scope but are not initialized.
const also has a block scope. Variables declared with const are similar to let in terms of scoping rules.
It is not hoisted outside the block.
Variables declared with const cannot be reassigned. They must be assigned a value at the time of declaration, and that value cannot be changed afterward.
function constDemo() { if (true) { const count = 7; } console.log(count); // Error - count is not defined (block-scoped) } console.log(count); // Error - count is not defined (block-scoped)
Variables declared with const are hoisted to the top of their block scope but are not initialized.
Avoid using `var` in favour of `let` and `const` for better scoping and to avoid hoisting-related issues.
Use `const` when the value of the variable should not be reassigned.
Use `let` when you expect to reassign the variable.