Understanding JavaScript var, let, and const

Learn how var, let, and const differ in scope, hoisting, and mutability. Clear code examples, best practices, and common pitfalls to write safer, modern JavaScript.

JavaScripting
JavaScripting Team
·5 min read
Declaring JS Variables - JavaScripting
Photo by Grooveaddictedvia Pixabay

Overview: var, let, and const

JavaScript offers three keywords for declaring variables: var, let, and const. Each has distinct scoping rules, hoisting behavior, and mutability implications. Understanding these differences helps you write clearer, more maintainable code and reduces subtle bugs that often surface in larger codebases. In this section we set up the mental model for when to use each declaration and what you should expect at runtime.

JavaScript
function demo() { var a = 1; // function-scoped let b = 2; // block-scoped const c = 3; // block-scoped, read-only binding a = 10; // allowed // b = 20; // allowed (reassignment) // c = 30; // TypeError: assignment to constant variable console.log(a, b, c); }
  • Use var sparingly, typically only for legacy code paths or specific function-scoped scenarios.
  • Prefer let for values that will change within a block.
  • Prefer const for bindings that never rebind after initialization.

Why this matters: adopting a consistent convention reduces mental overhead and makes code easier to reason about, especially in asynchronous contexts where scope boundaries can be tricky.

Related Articles