Storing Data
Variables: Your Data Containers ๐ฆ
Why this matters: almost everything you do in code depends on naming and storing values. Clear, well-chosen variables make code readable, maintainable, and easy to change.
Variables are named boxes that hold values you want to reuse or change later.
Why Do We Need Variables?
- To avoid repeating the same literal value everywhere
- To make code easy to update in one place
- To store results of calculations for later steps
Imagine you have a labeled box where you can store things. In programming, those boxes are variables.
// Without variables (bad)
console.log("Welcome, Alex!");
console.log("Alex, you have 5 messages");
console.log("Goodbye, Alex!");
// With variables (good!)
let name = "Alex";
console.log("Welcome, " + name + "!");
console.log(name + ", you have 5 messages");
console.log("Goodbye, " + name + "!");
Now if you want to change "Alex" to "Sarah", you only change ONE line!
Creating a Variable
let name = "Sarah";
let age = 25;
let isStudent = true;
Breaking It Down
let name = "Sarah";
โ โ โ
โ โ โโโ The value you're storing
โ โโโ The name you give your box (choose any name!)
โโโ "let" means "create a new variable"
Using Variables
Once created, just use the name (no quotes!):
let city = "London";
console.log(city); // Shows: London
console.log("I live in " + city); // Shows: I live in London
Variable Naming Rules
โ
Good names: userName, totalPrice, isLoggedIn
โ Bad names: 1stPlace (can't start with number), user name (no spaces)
Your Turn!
Create a variable called city that stores the text "London"