JavaScript const vs let vs var: Which Should You Use?

Modern JavaScript gives developers three ways to declare variables: const, let, and the older var. Understanding their differences prevents subtle bugs, especially when code uses loops, callbacks, modules, or asynchronous operations.

const

Use const when the variable binding should not be reassigned.

const apiUrl = "/api/products";
const pageSize = 20;

A const variable cannot be assigned a new value, but objects and arrays declared with const can still be modified.

const user = { name: "Dhilip" };
user.name = "Developer"; // valid
// user = {};             // invalid

let

Use let when the binding must change later.

let page = 1;
page++;
page = 2;

Unlike var, let is block scoped, which makes it safer inside loops and conditional blocks.

var

var is function scoped and follows older JavaScript declaration rules. New application code should normally prefer const or let.

if (true) {
    var message = "hello";
}

console.log(message); // still accessible

Block Scope

let and const exist only inside the block where they are declared.

if (true) {
    let count = 10;
    const name = "Algolassi";
}

// count and name are not available here

Hoisting and the Temporal Dead Zone

Declarations are processed before execution, but let and const cannot be accessed before their declaration. Accessing them early results in a temporal dead zone error.

console.log(value); // ReferenceError
let value = 10;

Practical Rule

Common Mistake

Do not choose let simply because the value might conceptually change. Choose it only when the variable binding is actually reassigned. This makes code easier to reason about and safer to refactor.

Conclusion

For modern JavaScript, const should be the default, let should be used for intentional reassignment, and var should generally remain in legacy code. This simple rule eliminates many scope-related surprises.

Back to Algolassi Tutorials

🤖 AlgoLassi Assistant Have a question about this tutorial?

Ask AlgoLassi and get an answer plus the tutorials worth studying next.

Ask a question

đŸ’Ŧ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.