Understanding var, let, and const in JavaScript
This article explains the differences between JavaScript's var, let, and const declarations, covering their scopes, hoisting behavior, and mutability, and provides clear code examples for each. It also highlights how const variables can still be modified when they hold objects or arrays, helping developers choose the right keyword for reliable code.
In JavaScript we often use var , let , and const to declare variables. They have important differences, and this article helps you understand them with clear code examples.
1. var keyword:
var was introduced in ES5. Variables declared with var have function scope, meaning they are visible throughout the function in which they are declared.
<code>function example() {
var x = 10;
console.log(x); // 10
}
console.log(x); // ReferenceError: x is not defined</code>In the example, variable x is visible inside the example function but not outside.
var also suffers from hoisting, allowing the variable to be accessed before its declaration.
<code>console.log(x); // undefined
var x = 10;</code>2. let keyword:
let was introduced in ES6. Variables declared with let have block scope, meaning they are visible only within the nearest enclosing block.
<code>function example() {
let x = 10;
if (true) {
let x = 20;
console.log(x); // 20
}
console.log(x); // 10
}
console.log(x); // ReferenceError: x is not defined</code>In the example, x is redeclared inside the if block, but the outer x retains its original value.
let does not have the hoisting problem.
<code>console.log(x); // ReferenceError: x is not defined
let x = 10;</code>3. const keyword:
const was also introduced in ES6. Variables declared with const are constants, block‑scoped, and cannot be reassigned.
<code>const x = 10;
console.log(x); // 10
x = 20; // TypeError: Assignment to constant variable</code>However, const variables that hold objects or arrays remain mutable.
<code>const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
const obj = { name: "John" };
obj.age = 30;
console.log(obj); // { name: "John", age: 30 }</code>Through the examples you can see that while const prevents reassignment, the contents of objects and arrays can still be modified.
Summary:
var is function‑scoped; let and const are block‑scoped.
var is hoisted; let and const are not.
let and const behave similarly, but const variables cannot be reassigned.
Choosing the appropriate declaration keyword helps you write more reliable and maintainable code.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.