AI Hints
JavaScript · Lesson 6 of 138

const

Values that don't change.

⏱ 2 min read▶ Video at 5:30🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Some values should never change after you set them. Your birthday, the number of days in a week, or a website's address. For those, use const, short for constant.

const
From the video: const
  • Some values never change
  • Birthday, days in a week
  • const

Trying to change a constant

Const days in week equals seven. Reading it is fine. But if we try to give it a new value, JavaScript throws an error. Here we catch the error, so we can print its message. Run it.

app.jsjavascript
const daysInWeek = 7;
console.log("Days:", daysInWeek);

try {
  daysInWeek = 8;
} catch (error) {
  console.log("JavaScript says:", error.message);
}
Output
Days: 7
JavaScript says: Assignment to constant variable.

let or const?

Here's the modern rule. Use const by default, and only use let when you know the value will change, like a counter or a running total. It makes your code safer, because nothing changes by accident. You may also see var in older code. It's the old way, with some confusing behaviour, so avoid it.

keyvalue
constthe default
letwhen it will change
varold, avoid it
Whyno accidental changes

Summary

Const makes a variable that can't be reassigned. Use it by default, and let when the value changes. Next, naming variables well.

Key takeaways
  • const by default
  • let for changing values
  • Avoid var
Next up: Naming Variables — camelCase and rules