Variables in JavaScript
What is a Variable?
In JavaScript, a variable is like a container or a box where you can store data. Just as you might store a pair of shoes in a box labeled "Shoes", you store a piece of information (like a user's name or age) in a variable so you can use it later in your program.
Why do we need Variables?
When building web applications, you constantly deal with data: user inputs, scores in a game, prices in a shopping cart, etc. Variables allow you to hold onto this data, manipulate it, and display it dynamically on your webpage.
Declaring a Variable
To create a variable, you "declare" it. In modern JavaScript, we use let or const to declare variables (though var is the older way, which we'll discuss soon).
let myName = "Himanshu Dubey";
let myAge = 25;
console.log(myName); // Outputs: Himanshu Dubey
In the example above, myName is the name of the variable, and "Himanshu Dubey" is the value stored inside it.
We can also change the data inside the container later on (as long as we used let):
myAge = 26; // It's my birthday!
console.log(myAge); // Outputs: 26
In the next chapters, we will dive deeper into how to name these variables correctly and the differences between var, let, and const.
💡 Himanshu's Tip:
Always choose descriptive names over short abbreviations. let userScore = 100; is infinitely better than let us = 100;. Your future self will thank you when you read your code 6 months from now!
Interview Questions
- What is the main purpose of a variable in programming?
- Which keyword was traditionally used to declare variables before modern JavaScript (ES6)?
- Can you reassign a value to a variable declared with
let?