Avoid Magic Numbers in Writing Code

Sean Shaughnessy
2 min readMay 20, 2021

Let’s say you wanted to write an algorithm for shuffling a deck of cards in JavaScript. You might start with something like this:

for (let i = 0; i < 52; i++) {

// …


Notice anything wrong? Someone reading your code may not know how many cards are in a standard deck of cards. What if the number of cards changes? (Stardeck Poker, anyone?) Maybe you meant to shuffle a deck of tarot cards and made a mistake. For whatever reason, the number 52 is not clear. This is what’s known as a Magic Number in software development.

A Magic Number is an unnamed numeric literal that is missing context. According to Robert Martin’s Clean Code: A Handbook of Agile Software Craftsmanship, the avoidance of magic numbers has been prescribed since at least the 1960s. As shown in the intro, magic numbers make your code harder to read and maintain.

Fortunately, magic numbers are easy to fix. Just store the number in a named constant, like so: const DECK_SIZE = 52 However, naming things is one of the hardest things to do in programming. Even if you are working on something small, you should try to use constants instead of magic numbers.

Of course, this advice can be taken too far. It is better to use 2 instead of const EVEN = 2 when determining whether a number is even or odd. In a recent exercise, I probably didn’t need to define CENTS_PER_DOLLAR and just used 100 in a function that converted cents to dollars. Also don’t try to be clever and define something like this: const FIVE = 5 It might get past a linter, but it’s still a magic number.

Therefore, you should avoid using magic numbers in your codebase. Whether it’s a big project or a small algorithm, it will make your code cleaner and more professional.