JS Const
const declares a binding that can't be reassigned. The contents of objects and arrays can still change — const only locks the variable to its current value.
Binding vs. contents
JS
const PI = 3.14;
// PI = 3.14159; // ← TypeError: Assignment to constant
const items = [1, 2, 3];
items.push(4); // ✓ contents can change
// items = []; // ← TypeError: reassignment
const user = { name: "Ada" };
user.role = "admin"; // ✓ adding properties is fine
// user = {}; // ← TypeError
Truly freezing values
JS
const config = Object.freeze({
apiUrl: "/api",
timeout: 5000,
});
// config.timeout = 100; // silently ignored (throws in strict mode)
When to pick const
- Anything you only assign once — which is most variables.
- Function declarations bound to arrow functions.
- Imported modules:
import x from "./x.js"is implicitly const. - Loop bindings in
for…of/for…in(the loop creates a fresh binding each round).
Tip: Default to
const. Linters like ESLint will flag you to switch from let when you never reassign.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Const!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Declare a value that should never be reassigned.
PI = 3.14159;
Default modern choice.
Discussion
Loading…