Understanding Variables and Data Types in JavaScript
1. What Are Variables?
In programming, variables are like containers (or boxes) used to store information.
Just like you keep items in a box and label it, in JavaScript we store data in variables with a name.
Example in real life:
A box labeled Name stores
"John"A box labeled Age stores
25
Example in JavaScript:
let name = "John";
let age = 25;
Here:
namestores a text valueagestores a number
Variables help us store and reuse data in our program.
2. Declaring Variables (var, let, const)
JavaScript provides three ways to create variables.
1. var
The older way to declare variables.
var city = "Bangalore";
2. let
The modern and most commonly used way.
let age = 25;
You can change the value later.
let age = 25;
age = 26;
3. const
Used when the value should not change.
const country = "India";
If you try to change it:
country = "USA"; // Error
3. Primitive Data Types in JavaScript
JavaScript has some basic data types called primitive data types.
1. String (Text)
Used to store text.
let name = "Sintu";
Examples:
"Hello""JavaScript""Student"
2. Number
Used for numeric values.
let age = 22;
let price = 99.5;
Examples:
10453.14
3. Boolean
Represents true or false.
let isStudent = true;
Examples:
truefalse
Used mostly in conditions.
4. Null
Represents an empty or intentionally cleared value.
let data = null;
5. Undefined
Means the variable exists but has no value assigned yet.
let score;
console.log(score); // undefined
4. Difference Between var, let, and const
| Keyword | Can Change Value? | Modern Usage |
|---|---|---|
| var | Yes | Mostly avoided |
| let | Yes | Recommended |
| const | No | Used for fixed values |
Example:
let age = 20;
age = 21; // allowed
const birthYear = 2000;
birthYear = 2001; // error
5. What Is Scope? (Simple Explanation)
Scope means where a variable can be used in your code.
Example:
{
let message = "Hello";
console.log(message);
}
console.log(message); // Error
Here, message only exists inside the block { }.
Think of scope like a room:
- If you keep something inside the room, you can only use it inside that room.
Small Example
let name = "Sintu";
let age = 22;
const country = "India";
console.log(name);
console.log(age);
console.log(country);
Output:
Sintu
22
India
Assignment
Create variables for the following:
Name
Age
IsStudent
Example:
let name = "Rahul";
let age = 21;
let isStudent = true;
console.log(name);
console.log(age);
console.log(isStudent);
