JavaScript Const
The const keyword declares a block-scoped variable whose binding cannot be reassigned after it is set.
What const means
const creates a constant reference to a value. Once you assign a value at declaration, you cannot point that name at a different value later. Because of this, a const declaration must be given a value immediately; declaring one without assignment is a syntax error.
A const cannot be reassigned
<!DOCTYPE html>
<html>
<body>
<h2>A const cannot be reassigned</h2>
<script>
const birthYear = 1990;
// birthYear = 1991; // TypeError: assignment to constant variable
console.log(birthYear); // 1990
</script>
</body>
</html>Note: const must be initialised on the same line it is declared. Writing const total; on its own throws a SyntaxError because there is nothing to bind the name to.
Constant reference, not constant contents
A common misunderstanding is that const makes a value unchangeable. What it actually locks is the binding between the name and the value. If that value is an object or array, its internal contents can still be modified; you simply cannot swap in a completely different object.
Objects and arrays can still change
<!DOCTYPE html>
<html>
<body>
<h2>Objects and arrays can still change</h2>
<script>
const user = { name: "Sam" };
user.name = "Alex"; // allowed: we mutate the object
user.age = 30; // allowed: adding a property
// user = {}; // NOT allowed: reassigning the binding
const colors = ["red"];
colors.push("blue"); // allowed
console.log(user, colors);
</script>
</body>
</html>const behaviour at a glance
Why prefer const
- It signals clear intent: this value is not meant to change.
- It prevents accidental reassignment bugs the engine catches for you.
- Like let, it is block-scoped and safe from the pitfalls of var.
- Using const by default leaves let to mark the few values that truly vary.
const in everyday code
<!DOCTYPE html>
<html>
<body>
<h2>const in everyday code</h2>
<script>
const TAX_RATE = 0.2;
const prices = [40, 60, 100];
const subtotal = prices.reduce((sum, p) => sum + p, 0);
const total = subtotal + subtotal * TAX_RATE;
console.log(total); // 240
</script>
</body>
</html>Note: A widely followed guideline: declare every variable with const first, and switch it to let only if you later find you must reassign it.