What is a Variable?
A variable is like a box where we keep something. We give the box a name (a label), and we put a value inside it. Later, we can look inside the box, use the value, or change it to something else.
For example, think of a school bag. The bag stays the same, but what you put inside it can change. Today you might put books, tomorrow you might put lunch. The bag is like the variable, and whatever is inside it is like the value.
let studentName = "Abishek";
let studentAge = 21;
Here, studentName is a box that holds the text "Abishek". studentAge is a box that holds the number 21.
Variable Keywords in JavaScript
JavaScript has three keywords to create a variable:
- var – the old way of creating a variable.
- let – the modern way, used when the value can change.
- const – the modern way, used when the value should not change.
How to Declare and Assign a Variable
Declaring means creating the variable. Assigning means putting a value inside it.
You can do both in one line:
let city = "Chennai";
Here, city is declared and "Chennai" is assigned to it at the same time.
You can also do it in two separate steps:
let city; // declaring (box created, but empty)
city = "Chennai"; // assigning (value put inside the box)
With const, you must assign a value at the same time you declare it. You cannot leave it empty and fill it later.
const country = "India"; // correct
Rules for Naming a Variable
- Start with a letter,
_, or$. Do not start with a number. - No spaces allowed. Use camelCase instead, like
studentName. - Do not use JavaScript reserved words like
let,const, orifas names. - Names are case-sensitive, so
ageandAgeare two different variables. - Choose names that describe what the variable holds, like
studentAgeinstead ofa.
Real-Life Examples
- Bank balance – This changes when you add or spend money.
- Shopping cart total – This changes when you add or remove items.
- Traffic light color – This changes from red to green to yellow.
- Roll number – This does not change once it is given to you.
let, const, and var
- Use let when the value can change (like a shopping cart total).
- Use const when the value should not change (like a roll number).
- var is the old way of making variables. Today, most people use let and const instead.
Naming Variables
Always give your variables clear names. A name like studentName is easy to understand. A name like x does not tell us anything.
Conclusion
Variables help us store information in a program. let is for values that change, const is for values that stay the same, and var is the old way. Once you practice this, choosing the right one becomes easy.
Top comments (0)