Understanding Variables and Data Types in JavaScript!!

π§Ύ What Are Variables and Why Are They Needed?
A variable is a container used to store data.
We need variables because:
To store user input
To store numbers (like age, marks, price)
To store text (like name, city)
To reuse values later in the program
Without variables, we cannot build real applications.
βοΈ How to Declare Variables in JavaScript
In JavaScript, we declare variables using:
varletconst
πΉ Using var (Old Way)
var name = "Bhavesh";
πΉ Using let (Modern Way)
let age = 20;
You can change its value later:
age = 21;
πΉ Using const (Constant Value)
const country = "India";
You cannot change it later:
country = "USA"; // β Error
π§© What Are Data Types?
A data type tells JavaScript what kind of value we are storing inside the variable.
Letβs understand with simple examples:
| Example | Data Type |
|---|---|
| "Bhavesh" | String |
| 20 | Number |
| true | Boolean |
πΉ Primitive Data Types (Basic Ones)
1οΈβ£ String (Text)
Used for names, messages, etc.
let name = "Bhavesh";
π Text must be inside quotes " " or ' '.
2οΈβ£ Number
Used for numbers (both integer and decimal).
let age = 20;
let price = 199.99;
3οΈβ£ Boolean
Used for true/false values.
let isStudent = true;
π Mostly used in conditions.
4οΈβ£ Null
Represents intentional empty value.
let middleName = null;
It means: "I know there is no value right now."
5οΈβ£ Undefined
When a variable is declared but not given any value.
let city;
console.log(city); // undefined
π Basic Difference Between var, let, and const
Hereβs a simple comparison:
| Feature | var | let | const |
|---|---|---|---|
| Can Reassign? | β Yes | β Yes | β No |
| Block Scope? | β No | β Yes | β Yes |
| Recommended? | β Avoid | β Yes | β Yes |
π In modern JavaScript, always prefer let and const.
π What is Scope?
Scope means:
π Where your variable can be used.
Think of it like a room πͺ.
If you keep a box inside a room, you can only access it inside that room.
Example:
{
let age = 20;
console.log(age); // β
Works here
}
console.log(age); // β Error (outside block)
Because let and const follow block scope.
var does not follow block scope, which can sometimes create confusion β thatβs why we avoid it.
π Showing How Values Can Change
let score = 50;
score = 80; // β
Allowed
const total = 100;
total = 200; // β Not allowed
π let can change
π const cannot change
π§ͺ Assignment (Practice Now!)
Try this in your browser console or VS Code:
1οΈβ£ Declare these variables:
Name
Age
IsStudent
Example:
let name = "Bhavesh";
let age = 20;
let isStudent = true;
console.log(name);
console.log(age);
console.log(isStudent);
2οΈβ£ Now try this:
Change the value of
ageTry changing the value of a
constvariableObserve what happens π
π Quick Visual Comparison
var vs let vs const
var β Old, avoid using
let β Can change value
const β Cannot change value
π Simple Scope Visualization
Global Area
|
|-- Block {
let variable β works only here
}
