Ad space (banner)
🟨JavaScript Lessons
Lesson 20 / 69

Constants (Making Read-Only Values with const)

In this lesson you'll learn how to make constants in JavaScript using const, so you can prevent accidental value changes and write safer code. This is for people searching "JavaScript const let difference" or "JavaScript how to make a constant."

A variable created with const throws an error if you try to change its value later. This guards against the bug of accidentally overwriting a value, so the basic rule is: use const instead of let whenever you don't plan to change the value. The recommended approach in real projects is: use const by default, and only switch to let once you find you actually need to reassign it.

The sample code declares a constant called MAX_SCORE, displays its value, and then deliberately triggers an error by attempting to reassign it with MAX_SCORE = 200. Since this is caught with try...catch, you can see exactly what the error message looks like. Writing a constant's name in uppercase with underscores, like MAX_SCORE, is a naming convention used across many languages to signal "a value that doesn't change."

A common beginner stumbling block is that even with const, the "contents" of an object or array declared with it can still be changed. What const prohibits is only "reassigning the variable itself" — changing an object's property or an array's elements is perfectly allowed. Without understanding this distinction, it's easy to get confused wondering "why did the contents change even though it's const?"

In real development, "use const by default" is a widely established basic rule across many teams, meant to prevent unintended changes. It's such a valued habit that code review sometimes flags a value that should never actually change but was declared with let instead.

Even when an object or array is declared with const, if you want to prevent its contents from being changed too, more strictly, you use Object.freeze(). Combining const and Object.freeze() prevents both reassignment of the variable and changes to its properties.

A variable declared with let can not only be reassigned deliberately, but also accidentally overwritten inside a loop without you noticing. To prevent this kind of accident too, it's a good habit to think in the order "start with const, switch to let only if necessary."

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)