const Keyword
Overview
const stands for 'constant'. Like let, it is block-scoped, but it has one major rule: it cannot be reassigned.
In modern JavaScript, const should be your default choice. Only use let if you absolutely know the variable's value needs to change later.
Syntax
Once a primitive value is assigned to a const variable, it is locked in forever.
const API_URL = "https://api.github.com";
API_URL = "https://google.com";
// TypeError: Assignment to constant variable.const prevents reassignment of the variable identifier. It does NOT freeze the contents of objects or arrays. You can still mutate their internal properties.
const user = { name: "Kartik", age: 22 };
// This is ALLOWED!
user.age = 23;
// This is NOT ALLOWED!
user = { name: "Aman", age: 25 }; // TypeErrorCommon Pitfalls
- Thinking
constmakes objects completely immutable. It only prevents reassigning the variable to a new object. (To truly freeze an object, useObject.freeze()). - Forgetting to initialize a
constvariable upon declaration (const x;throws an error immediately).
Interview Questions
Always default to 'const'. It communicates to other developers that this variable should never be reassigned, reducing bugs. Only switch to 'let' when you realize you need to update the value later (like in a for-loop counter).
Real-World Example
Developers use const for DOM elements, API configuration, and imported modules to ensure they aren't accidentally overwritten.
const submitBtn = document.getElementById("submit");
const MAX_RETRIES = 3;
// We know for a fact these won't change anywhere in the code.Check Your Knowledge
Test your understanding of const Keyword with these quick questions.