4 min read
ā¢Question 1 of 50easyWhat is the difference between let, const, and var?
Understanding variable declarations in JavaScript.
What You'll Learn
- Differences between var, let, const
- Scoping rules
- Best practices
Comparison
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Redeclare | Yes | No | No |
| Reassign | Yes | Yes | No |
| Hoisting | Yes (undefined) | TDZ | TDZ |
Examples
code.jsJavaScript
// var - function scoped
function test() {
var x = 1;
if (true) {
var x = 2; // same variable
}
console.log(x); // 2
}
// let - block scoped
function test2() {
let y = 1;
if (true) {
let y = 2; // different variable
}
console.log(y); // 1
}
// const - cannot reassign
const z = 1;
z = 2; // Error!Best Practice
Prefer const by default, use let when reassignment needed, avoid var.