JS Const
JavaScript const: Constant Bindings and Object Mutation
The const keyword declares a block-scoped variable whose binding cannot be reassigned after initialization. You must assign a value to a const variable on the exact line you declare it.
Binding Immutability vs. Value Mutation
Many learners think const makes an object or array completely read-only. In reality, const locks the pointer connecting the variable name to its value in memory.
- Primitives (
number,string,boolean): Cannot be reassigned or mutated, because primitive values are immutable. - Objects and Arrays: You cannot point the
constvariable to a brand-new object, yet you can still update properties or push items inside it.
Practical const Example with Object.freeze()
If you want to prevent accidental property changes on a configuration object, combine const with Object.freeze().
const apiConfig = {
baseUrl: "https://api.example.com",
timeoutMs: 3000,
};
// Allowed: mutating a property inside a const object
apiConfig.timeoutMs = 5000;
console.log("Updated timeout:", apiConfig.timeoutMs);
// True shallow immutability with Object.freeze
const roles = Object.freeze({ ADMIN: "admin", EDITOR: "editor" });
console.log("Role:", roles.ADMIN);
When to Use const
Use const for configuration constants, imported modules, function expressions, objects, arrays, and any computed value you do not replace. Defaulting to const makes your codebase easier to reason about because bindings stay stable.
Common Mistakes to Avoid
- Declaring
constwithout a value: Writingconst taxRate;throws aSyntaxErrorimmediately. Always initialize on the same line. - Reassigning a
constvariable: TryingmaxRetries = 5onconst maxRetries = 3throws aTypeError: Assignment to constant variable. - Assuming
Object.freeze()is deep:Object.freeze(user)locks top-level keys only; nested objects insideuser.addresscan still change unless frozen recursively.
Frequently Asked Questions
Can I push items into an array declared with const?
Yes, const tags = ["js"]; tags.push("es6"); works because tags still points to the exact same array in memory. Only tags = ["node"] is blocked.
Does const improve JavaScript performance?
Modern engines optimize both let and const well, so speed is nearly identical. The main benefit of const is preventing accidental reassignment bugs for humans.
How do I make a const object deeply immutable?
You can clone with structuredClone() when updating state, or recursively call Object.freeze() on nested objects in strict mode.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.