JavaScript Variables
In programming, a Variable is a container for storing data values. Imagine you are moving into a new house; you put your things into boxes and put a label on each box so you know what's inside.
Variables work exactly like that!
1. How to Create a Variable
To create (or "declare") a variable in JavaScript, we follow a simple pattern:
let name = "Ajay";
let: The keyword that tells the computer we are creating a variable.name: The unique name of the box (the label).=: The assignment operator (it puts the value into the box)."Ajay": The actual data being stored.
2. let vs const
In modern JavaScript, we have two main ways to create variables. The choice depends on whether the value will change later.
- let (Changeable)
- const (Constant)
Use let when the value of the variable will change later in your program.
let score = 0;
score = 10; // This is allowed!
Use const when the value should never change. It stands for "Constant."
const birthYear = 2000;
birthYear = 2005; // ❌ ERROR! You cannot change a constant.
3. Rules for Naming Variables
You can't just name your variables anything. JavaScript has a few strict rules:
- No Spaces: Use
userAge, notuser age. - Camel Case: In JS, we start the first word with a lowercase letter and every word after with a Capital (e.g.,
isUserLoggedIn). - Start with Letters: Names cannot start with a number.
- Meaningful Names: Don't use
let x = "Apple". Instead, uselet fruit = "Apple". It makes your code easier to read!
4. Using Variables
Once you store a value, you can use the variable name instead of the value itself.
let city = "Mandsaur";
console.log("I live in " + city);
// Output: I live in Mandsaur
city = "Indore";
console.log("Now I live in " + city);
// Output: Now I live in Indore
Let's Practice: The Greeting Script
Try writing this in your script.js:
- Create a variable called
developerNameand store your name in it. - Create a variable called
totalProjectsand store a number (like5). - Use
console.logto print a message combining both.
const developerName = "A Master"; // Using const because your name doesn't change often
let totalProjects = 3; // Using let because you will build more!
console.log("Hello, my name is " + developerName);
console.log("I have built " + totalProjects + " projects.");
Most professional developers use const for everything by default. They only switch to let if they realize they absolutely need to change the value later. This prevents bugs!
varYou might see some older tutorials using the keyword var. At CodeHarborHub, we avoid var because it is old and can cause strange bugs in your code. Stick to let and const!