
Introduction
JavaScript is one of the most popular programming languages, and variables are its foundation. Without variables, you cannot store or manipulate data in your application.
In this guide by TechYantram, you will learn everything about JavaScript variables including var, let, const, scope, hoisting, and best practices.
What is a Variable in JavaScript?
A variable is a container used to store data values.
let company = "TechYantram";
Here:
company→ variable name"TechYantram"→ value
Types of Variables in JavaScript
🔹 var (Old Method)
var age = 25;
- Function scoped
- Can be redeclared
- Hoisted
🔹 let (Modern Method)
let city = "Delhi";
- Block scoped
- Cannot be redeclared
- Can be updated
🔹 const (Constant)
const pi = 3.14;
- Block scoped
- Cannot be reassigned
- Best for fixed values
Difference Between var, let, const
| Featurevarletconst | |||
| Scope | Function | Block | Block |
| Redeclare | Yes | No | No |
| Reassign | Yes | Yes | No |
| Hoisting | Yes | TDZ | TDZ |
Variable Naming Rules
- Must start with letter,
$, or_ - Cannot start with number
- Case-sensitive
- Avoid reserved keywords
let userName = "Goutam";
Dynamic Typing
JavaScript is dynamically typed:
let value = 10; value = "Hello"; value = true;
Variable Scope
Global Scope
let globalVar = "Available everywhere";
Block Scope
{
let blockVar = "Inside block";
}
Function Scope
function demo() {
var x = 10;
}
Hoisting Explained
console.log(a); // undefined var a = 5; console.log(b); // Error let b = 10;
Real Example
const user = "Goutam";
let balance = 1000;
balance += 500;
console.log(`${user} has ₹${balance}`);
Best Practices
- Use
constby default - Use
letwhen needed - Avoid
var - Use meaningful names
- Follow camelCase
Common Mistakes
- Using
var - Redeclaring variables
- Ignoring scope
- Poor naming