Lesson · JavaScript Basics

Variables with let and const

Names make values easier to reuse, and declaration choices communicate how a name is used.

What you will learn

  • Declare a value with const
  • Use let for reassignment
  • Avoid accidental global variables

Declare names explicitly

Use const when a name will not be reassigned and let when its binding needs to change. Both are block-scoped, so a name belongs to the nearest pair of braces that contains its declaration. This makes accidental changes and collisions easier to reason about than old var behavior.

Const does not freeze objects

A const binding cannot be reassigned, but if it refers to an object or array, the object's contents may still be changed. The declaration protects the binding, not every nested value. If a value must be immutable, use a suitable data design rather than assuming const freezes it.

Choose descriptive names

Names should explain the value's role, such as lessonCount rather than x. JavaScript identifiers are case-sensitive and cannot contain spaces. Use camelCase for most local variables in ordinary JavaScript code and avoid reserved words that already have language meaning.

Reassignment is a new value

A let variable can be assigned again later. The program reads its current value at the point each statement runs. Keep state changes visible and local; changing one name from unrelated meanings makes later conditions much harder to follow.

Keep bindings in the smallest useful scope

Declare a value near the code that uses it, inside a function or block when possible. Smaller scope reduces the chance that an unrelated statement changes the same name. A let declaration cannot be read before its declaration runs, so place initialization before use rather than relying on hoisting behavior.

Javascript example
const course = 'JavaScript';
let completedLessons = 2;
completedLessons = completedLessons + 1;
console.log(`${course}: ${completedLessons} lessons`);
Expected output
JavaScript: 3 lessons

Practice exercise

Store a course name in a const and a completed lesson count in a let, then increase the count and log both.

Show a hint

Use a template literal to format the output.

Show one possible solution

Declare const course = 'CSS'; let completed = 1; then increment completed and log `${course}: ${completed}`.

Quick check

Can a const array have an item appended?

Frequently asked questions

Should I use var in new code?
<p>For beginner examples, prefer const by default and let when reassignment is needed. They have clearer block scope than var and reduce surprising behavior.</p>