How to use variables (let, const, var)

Prefer const by default

const prevents reassignment of the binding. Use it when the name should continue to refer to the same value.

const courseName = "JavaScript basics";
const lessons = 22;
console.log(courseName, lessons);

Use let for reassignment

let is block-scoped and suits counters or state that deliberately changes.

let score = 0;
score = score + 10;
score += 5;
console.log(score); // 15

Understand const objects

const does not freeze an object. Its properties may change, but the variable cannot be assigned another object.

const user = { name: "Mina", points: 0 };
user.points += 1;
console.log(user);

// user = {}; // TypeError

Know why var is usually avoided

  • var is function-scoped rather than block-scoped
  • var declarations are hoisted in ways that can surprise beginners
  • Use let for changing values and const otherwise
  • Choose descriptive camelCase names; identifiers are case-sensitive