What is a Variable?
A variable is like a labeled box that stores a value. Instead of writing the number 25 everywhere in your code, you store it once and refer to it by name. When the value needs to change, you change it in one place.
💡 Real-world analogy
Think of a variable as a sticky note with a label. The label is the variable name, and what you write on the note is the value.
Three Ways to Declare Variables
JavaScript gives you three keywords to create variables:
let — The Default Choice
- Use this when the value will change later
- Modern and block-scoped (we'll explain scope later)
- This is what you'll use most of the time
const — For Values That Don't Change
- Use this when the value should never change
- Most variables in modern JS are
const - Signals your intent clearly to other developers
var — The Old Way (Avoid This)
- Behaves inconsistently with scopes
- Causes bugs that are hard to track down
- Don't use it in new code
Rule of thumb
Default to
const. Switch to let only when you know the value needs to change. Never use var in new code.
Variable Naming Rules
- Names can contain letters, digits, underscores (
_), and dollar signs ($) - Must begin with a letter, underscore, or dollar sign (not a number)
- Case-sensitive:
scoreandScoreare different variables - Use
camelCasefor multi-word names:playerName,highScore - Avoid reserved words:
let,const,if,for, etc.
⚠️ Common mistake
Trying to reassign a
const variable throws a TypeError. If you get this error, the variable probably should have been let.
Quick Quiz
1. Which keyword should you use for a value that will never change?
2. Which of these is a valid variable name?
3. What happens when you try to reassign a const variable?
Summary
- Use
constby default,letwhen reassignment is needed - Avoid
varin new code - Variable names should be descriptive and use
camelCase - Every variable has a value, which can be a String, Number, Boolean, etc.
