The const Keyword
const declares a variable that cannot be reassigned.
Syntax
const PI = 3.14159;const declares a constant reference. Once assigned, it cannot be reassigned. Like let, it is block-scoped.
Objects and arrays
A const object or array cannot be reassigned, but its contents can still be changed. The binding is constant, not the data inside.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- Define an API base URL that must never change throughout the application lifecycle.
- Store a configuration object for a third-party SDK where the reference should stay fixed.
- Declare DOM element references obtained once at startup that should not be re-pointed.
More examples
Immutable primitive constant
Declares a numeric constant; attempting to reassign it throws a TypeError at runtime.
const MAX_RETRIES = 3;
console.log(MAX_RETRIES);
// MAX_RETRIES = 5; // TypeError: Assignment to constant variableConst object properties can change
Shows that const prevents rebinding the variable but still allows mutating the object's properties.
const config = { env: "production", port: 8080 };
config.port = 9090; // allowed β the reference is fixed, not the contents
console.log(config.port); // 9090Const array push is valid
Demonstrates that push works on a const array because it mutates the array, not the binding.
const colors = ["red", "green"];
colors.push("blue");
console.log(colors); // ["red", "green", "blue"]
Discussion