Variables: let and const
Store values with let and const, change them, and see what a variable holds before it is given a value.
JavaScript · beginner · 5 min · 7 steps · free
What you'll learn
- Declare variables with let and const
- Change a let variable
- Know that an unassigned variable is undefined
Variables.js
let score = 10;
const player = 'Ada';
score = score + 5;
let bonus;
console.log(player, score, bonus);
bonus = score * 2;
console.log(`${player} has ${bonus} bonus points`);
Step by step
let score = 10 creates a variable named score and puts 10 in it.player is a const: it will always hold "Ada".- The right side is worked out first, 10 + 5, then the result goes back into
score: 15. let bonus; creates a variable without a value. JavaScript gives it the special value undefined.- It prints
Ada 15 undefined. bonus changes from undefined to 30.- A template literal, between backticks, puts values straight into text with ${…}.
Common mistakes
- Reassigning a const
- Using var in new code
Best practices
- Use const by default; switch to let only when the value must change
Key takeaways
- let creates a variable you can change.
- const creates one you cannot reassign.
- A variable without a value is undefined.
Check yourself
const x = 1; x = 2; gives?
Answer: A TypeError. const cannot be reassigned.
let y; what is y?
Answer: undefined
Values and Types →
More in The Basics