Variables Explained in Depth - var, let, const
What are Variables?
Variables are containers.
They store information like name, age, score, etc.
Simple idea:
A variable is like a box that stores data.
Why we use Variables?
We use variables to store data so we can use it later.
Examples:
- Login form (username, password)
- Show message like "Welcome userName"
- Game score changes
- Shopping cart items
First store data, then use it.
Types of Variables
There are 3 types:
- var (old)
- let (recommended)
- const (fixed value)
Basic Difference
- var and let → value can change
- const → value cannot change
Example:
let name = "Anil";
name = "Peter"; // allowed
const city = "Delhi";
city = "Mumbai"; // not allowed
Syntax (How to create variable)
let data = "Anil";
- let → type
- data → variable name
- "Anil" → value
Important Rules (Naming)
You can use:
- letters (a to z)
- numbers (not at start)
- underscore (_)
- dollar ($)
Not allowed:
- space in name
- starting with number
- keywords like var, let, const
Best Practice
- Use let when value changes
- Use const when value is fixed
- Avoid var
Use meaningful names:
let userName = "Anil"; // good
let x = "Anil"; // not good
Why avoid var?
- Can declare same variable again
- Creates confusion
- Scope issues
Variable Value Change Example
let data = "Anil";
data = "Sameer"; // value changed
Const Example (Error Case)
const data = "Anil";
data = "Peter"; // error
Once value is set, it cannot change.
Data Stored in Variables
You can store:
- name
- number
- address
- any information
Code
<html>
<head>
<script>
let userName = "anil"
alert(userName)
</script>
</head>
<body>
<h1>Variables</h1>
</body>
</html>
What this code does:
- Creates a variable userName
- Stores value "anil"
- Shows alert with "anil"