</>
CompilerOnline
Open Interactive Editor

JS Variables: let, const, & var

JavaScript Variables

Variables are containers for storing data. In modern JavaScript, you have three keywords to declare variables: var, let, and const. Understanding the differences in scope and behavior between these keywords is vital for writing bug-free code.

  • var: Declares a function-scoped or globally-scoped variable. It is the original keyword and is prone to scope leaks since it ignores block structures like if statements or loops.
  • let: Declares a block-scoped local variable, restricting access strictly to the block where it is defined, preventing global pollution.
  • const: Declares a block-scoped read-only constant whose value cannot be reassigned after declaration.

Variables declared with var are hoisted to the top of their scope and initialized as undefined. In contrast, let and const variables are hoisted but not initialized, residing in a "Temporal Dead Zone" until their declaration is parsed.

While const prevents reassignment, it does not make objects immutable. Properties inside a constant object or array can still be altered. Best practice in modern JavaScript is to default to const, using let only when you expect the variable value to change.

Block Scope Leaks

Variables declared with var leak outside code blocks (such as if blocks or for loops) because they are only constrained by functions, whereas let and const restrict variables safely to the enclosing block.

javascript
if (true) {
    var leaked = "I leak outside block";
    let blockConstrained = "I am block safe";
}
console.log("Leaked:", leaked);
javascript
const PI = 3.14159;
let radius = 5;
var locationName = "Main Studio";

let area = PI * radius * radius;
console.log("Circle Area:", area);
console.log("Studio location:", locationName);