Why Do We Need to Store Data?
Imagine having no place to keep your belongings. Most of the time, you would lose them or struggle to find them when you need them.
Programs face the same problem. Without a place to store data, a program cannot remember anything while it is running—not user information, not calculations, and not the current state of the application.
This is where memory comes in.
Where Is Data Stored?
There are several ways to store data, including:
- RAM (Random Access Memory)
- Hard Disk / SSD
- Cloud Storage
In this lesson, we’ll focus on RAM, since it is where most program data is stored while the application is running.
What Is a Variable?
In the previous lesson, we used the following example:
if (age > 18) { console.log("Pass");}We saw the name age, but we didn’t explain what it actually was.
A variable is simply a container that stores a value so it can be used later.
For example:
var age = 19;Here, we created a variable named age and stored the value 19 inside it.
Why Is It Called a Variable?
If you remember the previous lesson about keywords, we used the keyword var.
This keyword creates a variable, which gets its name because its value can change during the execution of the program.
var age = 19;
age = 20;Initially, age stores 19, and later its value changes to 20.
What If the Value Should Never Change?
Sometimes a value should remain the same throughout the lifetime of a program.
In that case, we use a different keyword:
const age = 19;Notice that we used const instead of var. A constant is created when a value should not be reassigned after it has been initialized.
This highlights an important idea: we choose the appropriate keyword based on the behavior we want.
Where Are These Values Stored?
Whenever you create a variable or a constant, its value is stored in RAM while the program is running.
You can think of it like any application on your computer. When you launch a program, it occupies a portion of your computer’s RAM.
Once you restart your computer, every running application closes and the data stored in RAM disappears because RAM is temporary memory.
Variables and constants behave the same way—they exist only while the program is running and are removed from memory once execution ends.
Key Takeaways
- Programs need to store data while they are running.
- A variable stores a value that can change over time.
- A constant stores a value that is not reassigned after initialization.
- Variables and constants are stored in RAM during program execution.
- Data can also be stored in other places, such as Hard Disks/SSDs and Cloud Storage, which you’ll learn about later.