Magic String
ELI5 — The Vibe Check
A magic string is a hardcoded string value buried in code with no explanation — like finding a mysterious note that says 'ADMIN_OVERRIDE_7742' deep in the auth logic. What does it mean? Who put it there? What happens if you change it? Nobody knows. Magic strings are magic numbers' equally evil twin. Use constants, enums, or config instead.
Real Talk
A magic string is an unnamed string literal used directly in code, making the code harder to understand, maintain, and refactor. Like magic numbers, they obscure intent and create duplication risks. The fix is extracting them into named constants, enums, or configuration. Common examples include status values ('active', 'pending'), role names, and error messages.
Show Me The Code
// Bad: magic strings everywhere
if (user.role === 'super_admin_v2') {
if (order.status === 'pending_review_3') {
sendEmail('order-confirmation-template-b')
}
}
// Good: named constants
const ROLES = { SUPER_ADMIN: 'super_admin_v2' } as const
const ORDER_STATUS = { PENDING_REVIEW: 'pending_review_3' } as const
if (user.role === ROLES.SUPER_ADMIN) {
if (order.status === ORDER_STATUS.PENDING_REVIEW) {
sendEmail(EMAIL_TEMPLATES.ORDER_CONFIRMATION)
}
}
When You'll Hear This
"What does 'XJ-7' mean in line 47? — It's a magic string, nobody knows." / "Replace all magic strings with an enum before this gets worse."
Related Terms
Code Smell
Code Smell is when code isn't technically broken but something feels off — like a 500-line function, a class named 'Manager' that does everything, or a com...
Constant
A constant is a box you seal shut after putting something in. You can look inside any time you want, but you can't swap out what's in there.
Enum
An enum is a named list of options that are all related.
Magic Number
A random number in your code with no explanation. Like writing `if (age > 17)` instead of `if (age > MINIMUM_AGE)`.
Refactor
Refactoring is cleaning and reorganizing your code without changing what it does — like tidying your room without throwing anything away.