Variables: let, const & var
Variables are labelled boxes that store data. Learn to create them the modern way.
What you will learn
- Declare variables with let and const
- Know when to use each
- Name variables well
Storing data
A variable stores a value under a name so you can use it later. Modern JavaScript uses two keywords: let (value can change) and const (value stays constant).
<script>
let score = 10; // can change later
const name = "Asha"; // cannot be reassigned
score = 20; // OK — let allows this
document.write(name + " scored " + score);
</script>Reading it line by line: let score = 10 makes a box named score holding 10. const name = "Asha" makes a sealed box holding the text "Asha". The line score = 20 refills the score box with a new value — allowed, because it was made with let. Finally we join the name and the new score with + and write the sentence to the page.
Note: Output:
Asha scored 20
(score shows 20, not 10, because we changed it. If we had tried name = "Ravi" the browser would throw an error, because const values cannot be reassigned.)
let vs const
| Keyword | Use when | Can reassign? |
|---|---|---|
const | The value should not change (default choice) | No |
let | The value will change (counters, totals) | Yes |
var | Old style — avoid in new code | Yes |
Tip: Best practice: reach for const by default. Only use let when you know the value needs to change. Avoid the old var — let/const are safer.
Naming rules
- Use camelCase:
firstName,totalPrice. - Start with a letter,
$or_— not a number. - Make names descriptive:
agenota. - Names are case-sensitive:
scoreandScorediffer.
Q. Which keyword should you use by default for a value that will not change?
✍️ Practice
- Create a
constfor your name and aletfor your age, then print a sentence using both. - Try reassigning a
constand read the error in the console.
🏠 Homework
- Declare five well-named variables about yourself (name, city, age, hobby, isStudent) and print them.