All tutorials
Basics

Variables: var, let, const

Store values with let and const. Avoid var in modern code.

1. Explanation

Variables are named containers for values. Use 'let' when a value will change, 'const' when it should never be reassigned, and avoid 'var' because it has confusing function-level scope and hoisting behavior. 'let' and 'const' are block-scoped (limited to the nearest { }).

2. Syntax

js
let name = "Aman";
const PI = 3.14159;
var old = "avoid me";

3. Example

Try it yourself
Console
Click Run to see output.

4. Expected output

output
19 India

5. Common mistakes

  • Reassigning a const → throws TypeError
  • Using var inside a loop and being surprised by leaked scope
  • Declaring the same let twice in the same block

6. Practice questions

  1. Declare a const for your birth year and a let for current year, then compute your age
  2. Try to reassign a const and read the error message
  3. Create three variables: name, age, isStudent and print them
→ Try more practice problems