Explain Codes LogoExplain Codes Logo

Const in JavaScript: when to use it and is it necessary?

javascript
best-practices
functions
performance
Alex KataevbyAlex Kataev·Jan 8, 2025
TLDR

Always prefer const over let while declaring variables. It immensely improves code predictability and maintainability. A const locking variable assignment doesn't mean it freezes objects or arrays. Contrarily, it guards the binding not the value.

const SPEED_OF_LIGHT = 299792458; // Usain Bolt: Hold my beer! const SETTINGS = { theme: 'dark' }; // The Dark Side approved! SETTINGS.theme = 'light'; // Jedi: 'There has been an awakening! Have you felt it?' // SPEED_OF_LIGHT = 300000000; // TypeError: Einstein: 'Told ya!'

Switch over to let only in scenarios where variable reassignment is inevitable. Otherwise, const should be your default choice.

When to wear the const hat

To inject predictability and avoid accidental reassignments, developers prefer const while declaring immutable variables or values not meant to be re-bound. Here's where it comes handy:

  • Declaring universal constants (ex: PI, SPEED_OF_LIGHT)
  • Indicating immutable imports in modules
  • Emphasizing immutable-by-default coding approach

Scope and initialization of const

Unlike var which has functional or global scope, const and let enjoy block scope, limiting their reach to the block, statement or expression where they're declared.

if (true) { const message = 'Hello! Const calling!'; console.log(message); // Hello! Const calling! } console.log(message); // ReferenceError: Const: 'You can't see me!'

An unassigned const declaration is a no-go and results in a syntax error.

const greeting; // SyntaxError: Const: 'Give me a value!'

const rules to code by

const is like a contract. Once a const variable is assigned a value, it's 'untouchable', ensuring code safety.

  • Using const while declaring functions avoids reassignments resulting in unexpected behavior:
const calculateArea = function(radius) { return Math.PI * radius * radius; }; // ... // calculateArea = someOtherFunction; // TypeError: Const: 'Keep your hands off!'
  • Group related constants as enumerations, improving readability:
const UserRole = { ADMIN: 'admin', GUEST: 'guest', USER: 'user' };

Performance gains using const

JavaScript engines are good at their job, they perform optimizations like dead code elimination when const is used. Although performance benefits are minimal given current engine optimizations, const actually helps improve runtime efficiency.

The objects are mutable Tightrope

Despite what the name implies, const doesn't make assigned values immutable. Reassigning a const value is forbidden, but objects and arrays can be mutated:

const book = { title: '1984', author: 'George Orwell' }; book.title = 'Animal Farm'; // Orwell: 'Here's looking at you, kid!'