Chapter 07

let, const and var

JavaScript provides let, const, and var for declaring variables, with different rules and scope behavior.

What is let, const and var?

  • let is useful when the variable value may need to be changed later.
  • const is used when a variable binding should not be reassigned.
  • var is the older variable declaration keyword and is generally avoided in modern JavaScript when let or const can be used.
  • let and const are block-scoped.

Syntax

let age = 20;
age = 21;

const country = 'India';

var oldStyle = 'Example';

Example

Try understanding this code before running it.
let marks = 70;
marks = 85;

const course = 'JavaScript';

console.log(marks);
console.log(course);

Important Points

  • Use let when a value needs to be reassigned.
  • Use const when reassignment is not required.
  • A const variable cannot be directly assigned a new value later.
  • Understanding the scope behavior of var is important when reading older JavaScript code.

Common Mistakes

  • Trying to reassign a const variable.
  • Using var everywhere instead of understanding let and const.
  • Ignoring variable scope.

Real-World Use

let and const are used throughout modern web applications for user data, counters, configuration values, and calculated results.

Practice Exercise

Practice: let and const
Create a let variable and change its value. Then create a const variable and try to understand why it cannot be reassigned.

Ready to write code?

Open the JavaScript editor and run your code with live output.

Try It Yourself →