Variables in JavaScript
Keywords: JavaScript variables, var let const, JavaScript basics
What are Variables?
Variables are containers that store data for later use.
Example:
javascriptCopyEditlet name = "Ali";
const age = 25;
var country = "Pakistan";

Three Ways to Declare Variables
| Keyword | Scope | Reassignment | Hoisting | Use Case |
|---|---|---|---|---|
| var | Function | Yes | Yes | Legacy code |
| let | Block | Yes | No | Changing values |
| const | Block | No | No | Fixed values |
Variable Scope
- Global Scope – Accessible anywhere in code
- Local Scope – Accessible only inside a function
- Block Scope – Accessible only within
{}
Example:
javascriptCopyEdit{
let blockVar = "Inside Block";
console.log(blockVar);
}
// console.log(blockVar); // Error
Hoisting
JavaScript moves var declarations to the top before execution, but let and const are not accessible before YouTube declaration.
Best Practices
- Always use
constunless the value changes - Use meaningful names like
userAgeinstead ofx - Avoid
var in modern code - Build a To-Do List App in Python – Console-Based Project for Beginners – 804
