JavaScript Variables (let, const, and var)

A comprehensive guide to variable declarations in JavaScript, covering let, const, and var, their differences, and best practices.

Last updated: 2024-12-15

Variables are fundamental building blocks in JavaScript, used to store and manipulate data. Understanding the different types of variable declarations - let, const, and var - is crucial for writing effective and maintainable JavaScript code.

Introduction

In JavaScript, we have three ways to declare variables:

  1. let: Introduced in ES6 (ECMAScript 2015), used for variables that can be reassigned.
  2. const: Also introduced in ES6, used for variables with constant values.
  3. var: The original way to declare variables in JavaScript, now less commonly used due to some functional quirks.

Let's dive into each of these in detail.

let

let allows you to declare variables that are limited in scope to the block, statement, or expression in which they are used.

Key characteristics:

  1. Block-scoped
  2. Can be reassigned
  3. Cannot be redeclared in the same scope
  4. Not hoisted

Example:

let x = 10;
x = 20; // This is allowed

if (true) {
  let y = 30; // y is only accessible within this block
  console.log(y); // Outputs: 30
}
console.log(y); // ReferenceError: y is not defined

let x = 40; // SyntaxError: Identifier 'x' has already been declared

const

const is used to declare variables whose values are never intended to change. It's also block-scoped like let.

Key characteristics:

  1. Block-scoped
  2. Cannot be reassigned
  3. Cannot be redeclared
  4. Must be initialized at declaration
  5. Not hoisted

Example:

const PI = 3.14159;
PI = 3.14; // TypeError: Assignment to a constant variable

const USER = {name: "John"};
USER.name = "Jane"; // This is allowed (mutating properties)
USER = {name: "Jane"}; // TypeError: Assignment to a constant variable

const COLORS; // SyntaxError: Missing initializer in const declaration

Note: While const prevents reassignment of the variable itself, it doesn't make its value immutable. For objects and arrays, the properties or elements can still be modified.

var

var is the oldest way to declare variables in JavaScript. It has some behaviors that can lead to unexpected results, which is why let and const are now preferred.

Key characteristics:

  1. Function-scoped or globally-scoped
  2. Can be reassigned
  3. Can be redeclared
  4. Hoisted to the top of its scope

Example:

var x = 10;
var x = 20; // This is allowed

function example() {
  var y = 30;
  if (true) {
    var y = 40; // Same variable as above
    console.log(y); // Outputs: 40
  }
  console.log(y); // Outputs: 40
}

console.log(z); // Outputs: undefined (not an error)
var z = 50;

Comparison

Here's a quick comparison of let, const, and var:

Featureletconstvar
ScopeBlockBlockFunction/Global
ReassignmentYesNoYes
RedeclarationNoNoYes
HoistingNoNoYes
Temporal Dead ZoneYesYesNo

Best Practices

  1. Use const by default. It makes your intentions clear and prevents accidental reassignments.
  2. Use let when you know the value of a variable will change.
  3. Avoid using var in modern JavaScript code.
  4. Declare variables at the top of their scope for better readability.
  5. Use descriptive variable names to make your code self-documenting.

Common Pitfalls and Gotchas

Temporal Dead Zone (TDZ)

Both let and const are subject to the Temporal Dead Zone. This means you can't access these variables before their declaration:

console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 10;

var Hoisting

var declarations are hoisted to the top of their scope, which can lead to unexpected behavior:

console.log(x); // Outputs: undefined
var x = 10;

// The above is interpreted as:
var x;
console.log(x);
x = 10;

Block Scope vs Function Scope

let and const are block-scoped, while var is function-scoped:

if (true) {
  var x = 10;
  let y = 20;
  const z = 30;
}
console.log(x); // Outputs: 10
console.log(y); // ReferenceError: y is not defined
console.log(z); // ReferenceError: z is not defined

Frequently Asked Questions

  1. Q: When should I use let vs const? A: Use const when the variable won't be reassigned, and let when it will. As a rule of thumb, start with const and change to let if needed.
  2. Q: Is there any performance difference between let, const, and var? A: In modern JavaScript engines, there's negligible performance difference. Choose based on scope and mutability needs, not performance.
  3. Q: Can I use let and const in older browsers? A: Older browsers might not support let and const. If you need to support these browsers, use a transpiler like Babel to convert your code to ES5.
  4. Q: Why is var considered harmful? A: var can lead to unexpected behavior due to hoisting and function-scoping. It's easier to introduce bugs, especially in larger codebases.
  5. Q: Can I change the properties of a const object? A: Yes, const only prevents reassignment of the variable itself. The properties of a const object can still be modified.

Additional Resources

  1. MDN Web Docs: let
  2. MDN Web Docs: const
  3. MDN Web Docs: var
  4. JavaScript.info: Variables
  5. ESLint: Prefer const