The const Keyword

const declares a variable that cannot be reassigned.

Syntaxconst 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

Try it yourself
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.

Example Β· js
const MAX_RETRIES = 3;
console.log(MAX_RETRIES);
// MAX_RETRIES = 5; // TypeError: Assignment to constant variable

Const object properties can change

Shows that const prevents rebinding the variable but still allows mutating the object's properties.

Example Β· js
const config = { env: "production", port: 8080 };
config.port = 9090; // allowed – the reference is fixed, not the contents
console.log(config.port); // 9090

Const array push is valid

Demonstrates that push works on a const array because it mutates the array, not the binding.

Example Β· js
const colors = ["red", "green"];
colors.push("blue");
console.log(colors); // ["red", "green", "blue"]

Discussion

  • Be the first to comment on this lesson.
The const Keyword β€” JavaScript | SoundsCode