JavaScript Variables
Learn how variables work in JavaScript, understand var, let, and const, and know when to use each with practical examples.
Reading Time
12 min
Lesson
Lesson 4 of 48
What is a Variable?
A variable is a named container used to store data. Instead of writing the same value multiple times, you store it inside a variable and reuse it whenever required.
Declaring Variables
Console Output
Click “Run” to see the console output here.
var, let and const
Modern JavaScript recommends using let and const. Avoid using var in new projects because it behaves differently due to function scope and hoisting.
Comparison
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Redeclare | Yes | No | No |
| Reassign | Yes | Yes | No |
| Hoisted | Yes | Yes | Yes |
Example of let
Console Output
Click “Run” to see the console output here.
Example of const
Console Output
Click “Run” to see the console output here.
Best Practice
Use const by default. Only use let when the value needs to change. Avoid var in modern JavaScript development.
Common Mistake
Many beginners think const makes objects immutable. It only prevents reassignment of the variable reference. Object properties can still be modified.
Remember
Variable names are case-sensitive. userName and username are considered different variables.