Lesson 2
Why Variables?
Variables allow us to store data in memory with a name, so we can use it, update it, and work with it throughout our program.
Think of variables as labeled boxes where you can store items. You can change what’s inside the box, and use it whenever you want.
NameStores your name
AgeStores your age
ScoreStores your marks
Without variables, we have to write values again and again. If the value changes, we must change it everywhere!
Bad Example
// Calculate area of a rectangleconsole.log(10 * 5); // 50console.log(10 * 5 * 2); // 100console.log(10 * 5 * 2 + 10 * 5); // 150let length = 10;let width = 5;console.log(length * width); // 50console.log(length * width * 2); // 100console.log(length * width * 2 + length * width); // 150Easy to read, easy to update, easy to maintain.
Create variables for your name and age, then print them.
JavaScript
- Variables store data in memory.
- They give data a meaningful name.
- They help us reuse and update data easily.
- They make code readable and maintainable.
- ReusabilityUse the same data multiple times.
- MaintainabilityChange once, update everywhere.
- ReadabilityMakes code easy to understand.
- FlexibilityValues can be changed anytime.
Always use meaningful names so others (and your future self) can understand your code easily.
