Magic Strings

Published on 11/23/2025

Today I learned about a concept in programming called magic strings.
They’re basically hard-coded strings that appear in your code without any explanation or context.

At first, they seem harmless, but they can create a lot of problems:

if (user.role === "admin") { ... }  // ← magic string

The fix is simple: give that value a clear place to live.
For example, use constants or enums:

const ROLES = {
  ADMIN: "admin",
  USER: "user",
};

Now you can use them like this:

if (user.role === ROLES.ADMIN) {
  // Admin logic here
}

Now the code is easier to maintain, safer, and way more readable.

Magic strings look small, but removing them makes your code cleaner and your future self much happier.

back