JavaScript Variables Explained: var, let, const (Beginner Guide)
Variables in JavaScript:
var, let & const Explained
Everything you need to know about JavaScript variables — how to create them, the difference between var, let, and const, scope, hoisting, and when to use each one. Complete beginner guide!
What is a Variable in JavaScript? — The Complete Explanation
Before you can write any meaningful JavaScript program, you need to understand variables. A variable is one of the most fundamental concepts in all of programming — not just JavaScript. Every programming language in the world uses variables in some form.
In the simplest possible terms, a variable in JavaScript is a named container that stores a piece of data. Think of it exactly like a labeled box. You put something inside the box, you write a name on the label, and then you can find that box later using its name. You can also open the box, take out what's inside, replace it with something new, or read what's in it without changing anything.
For example, instead of writing the number 25 everywhere in your code, you store it in a variable called age. Now whenever you need that number, you just write age. If the age changes, you update it in one place and your entire program updates automatically. That is the power of variables.
In JavaScript, there are three keywords used to create (declare) variables: var, let, and const. Each one behaves differently — and understanding the differences between them is essential for writing correct, professional JavaScript code in 2026.
How to Declare a Variable in JavaScript — Basic Syntax
Declaring a variable means creating it and optionally assigning a value to it at the same time. The syntax in JavaScript is simple — write the keyword (var, let, or const), then the variable name, then an equals sign, then the value:
// Three ways to declare a variable in JavaScript var oldName = "Sara"; // old style — avoid in 2026 let age = 22; // modern — value can change const country = "Pakistan"; // modern — value cannot change // Use the variables console.log(oldName); // Sara console.log(age); // 22 console.log(country); // Pakistan // Declare without a value (only with var and let) let score; console.log(score); // undefined
Sara
22
Pakistan
undefinedNotice the last one prints undefined — that is JavaScript's way of saying "this variable exists, but it has no value assigned to it yet." This is an important concept we will explore further below.
JavaScript Variable Naming Rules — What Names Are Allowed?
You cannot name your variables anything you want. JavaScript has strict rules for what counts as a valid variable name. Breaking these rules will cause an immediate error:
name
myName
_hidden$price
user1
totalScore
1name — starts with numbermy-name — hyphens not allowedlet — reserved keyword
• Must start with a letter, underscore
_, or dollar sign $• Cannot contain spaces or hyphens
• Cannot be a reserved keyword like
let, const, function, return• JavaScript is case-sensitive —
Name and name are two different variables• Use camelCase convention:
firstName, totalScore, isLoggedIn
The var Keyword — The Old Way (Why You Should Avoid It)
var was the original way to declare variables in JavaScript — it existed from the very beginning in 1995. For many years, var was the only option. However, var has several confusing behaviors that cause bugs — which is exactly why let and const were introduced in ES6 (2015) to replace it.
In 2026, you should avoid using var in new JavaScript code. However, understanding it is still important because you will encounter it in older code, tutorials, and legacy projects.
Here are the three main problems with var:
// Problem 1 — var can be RE-DECLARED (no error!) var name = "Sara"; var name = "Ali"; // No error! Silently overwrites — causes hidden bugs console.log(name); // Ali // Problem 2 — var is FUNCTION scoped (not block scoped) if (true) { var message = "Hello!"; } console.log(message); // "Hello!" — var LEAKS outside the if block! ❌ // Problem 3 — var is HOISTED (moves to top, causes undefined) console.log(score); // undefined — no error, but confusing ❌ var score = 100;
The let Keyword — The Modern Way to Declare Variables
let was introduced in ES6 (2015) to fix all the problems with var. It is now the standard way to declare variables in JavaScript when the value needs to change later in your program. Use let for values like counters, user input, scores, and anything that gets updated.
let is block-scoped — this means a variable declared with let inside a block (inside { } curly braces) only exists within that block. It cannot leak out like var does. This makes your code much more predictable and safe.
// let can be UPDATED (value can change) let score = 50; score = 85; // ✅ Allowed — updating value console.log(score); // 85 // let CANNOT be re-declared in same scope let name = "Sara"; // let name = "Ali"; ← SyntaxError! ✅ Good — prevents accidents // let is BLOCK SCOPED — stays inside { } if (true) { let greeting = "Hello!"; console.log(greeting); // ✅ "Hello!" — works inside block } // console.log(greeting); ← ReferenceError — doesn't exist outside ✅ // let with loops — perfect use case for (let i = 1; i <= 3; i++) { console.log("Count: " + i); }
85
Hello!
Count: 1
Count: 2
Count: 3let when you need a variable whose value will change later — loop counters, user scores, form inputs, running totals, and anything that gets updated during your program.The const Keyword — For Values That Never Change
const stands for constant. Like let, it was introduced in ES6 (2015) and is block-scoped. The key difference: a variable declared with const cannot be reassigned after it is created. Once you set its value, that value is locked.
This might sound limiting, but it is actually a best practice. Using const communicates to other developers (and to your future self) that this value is intentionally fixed and should never change. It also prevents accidental reassignment bugs — a very common source of errors in larger programs.
An important detail: const does not mean the value is completely frozen. For objects and arrays, you can still modify their contents — you just cannot reassign the variable to a completely new value.
// const — value cannot be reassigned const PI = 3.14159; const country = "Pakistan"; const MAX_AGE = 120; console.log(PI); // 3.14159 console.log(country); // Pakistan // PI = 3; ← TypeError: Assignment to constant variable ✅ // const with ARRAYS — contents CAN be changed const colors = ["red", "blue"]; colors.push("green"); // ✅ Allowed — modifying contents console.log(colors); // ["red", "blue", "green"] // colors = ["yellow"]; ← TypeError — cannot reassign ✅ // const with OBJECTS — properties CAN be changed const user = { name: "Sara", age: 22 }; user.age = 23; // ✅ Allowed — modifying property console.log(user.age); // 23
3.14159
Pakistan
["red", "blue", "green"]
23const as your default choice. Only switch to let when you know the value will need to change. This is the modern best practice recommended by all professional JavaScript developers.Variable Scope in JavaScript — Where Can You Use a Variable?
Scope is one of the most important concepts to understand about JavaScript variables. Scope determines where in your code a variable can be accessed. JavaScript has three types of scope:
let globalVar = "I am global"; // Global scope — everywhere function myFunction() { let funcVar = "I am local"; // Function scope — only inside here console.log(globalVar); // ✅ Can access global console.log(funcVar); // ✅ Can access local if (true) { let blockVar = "I am block"; // Block scope — only inside if{ } console.log(blockVar); // ✅ Works inside the block } // console.log(blockVar); ← ReferenceError — block is over ✅ } myFunction(); console.log(globalVar); // ✅ Global works everywhere // console.log(funcVar); ← ReferenceError — function scope ✅
Hoisting — Why JavaScript Moves Variable Declarations Up
Hoisting is one of JavaScript's most misunderstood behaviors. It means JavaScript automatically moves variable and function declarations to the top of their scope before the code runs. This is why you can use a var variable before you declare it — and get undefined instead of an error. let and const are also hoisted, but they are NOT initialized — accessing them before declaration causes a ReferenceError.
// var HOISTING — gets undefined (confusing but no error) console.log(a); // undefined — hoisted but not initialized var a = 10; // let/const HOISTING — ReferenceError (safer behavior) // console.log(b); ← ReferenceError: Cannot access 'b' before initialization let b = 20; // Function declarations ARE fully hoisted — you CAN call before defining sayHello(); // ✅ Works! "Hello World!" function sayHello() { console.log("Hello World!"); }
var vs let vs const — Complete Comparison Table
Here is everything you need to know about the three variable keywords in one clear comparison table:
| Feature | var | let | const |
|---|---|---|---|
| Introduced | 1995 (ES1) | 2015 (ES6) | 2015 (ES6) |
| Scope | Function scope | Block scope | Block scope |
| Re-declare? | ✅ Yes | ❌ No | ❌ No |
| Re-assign? | ✅ Yes | ✅ Yes | ❌ No |
| Hoisted? | Yes (undefined) | Yes (TDZ error) | Yes (TDZ error) |
| Use in 2026? | ❌ Avoid | ✅ Yes | ✅ Yes (default) |
JavaScript Variable Best Practices — Write Code Like a Pro
Now that you understand all three keywords, here are the professional best practices for using variables in JavaScript that every serious developer follows:
// ✅ 1. Use const by default — switch to let only when needed const userName = "Sara"; const MAX_SCORE = 100; let currentScore = 0; // will change — use let // ✅ 2. Use meaningful, descriptive names (not x, y, z) const totalStudents = 30; // ✅ clear const x = 30; // ❌ what is x? // ✅ 3. Use camelCase for variable names const firstName = "Ahmed"; // ✅ camelCase const FirstName = "Ahmed"; // ❌ PascalCase (for classes only) // ✅ 4. Use UPPER_CASE for true constants const API_KEY = "abc123"; const MAX_RETRIES = 3; // ✅ 5. Declare variables at the top of their scope function calculateTotal(price, qty) { const TAX_RATE = 0.1; let total = price * qty; total += total * TAX_RATE; return total; } console.log(calculateTotal(50, 3)); // 165
165✅ Complete Summary — Variables in JavaScript (var, let, const)
π‘ var — old style, function-scoped, can be re-declared. Avoid in modern JavaScript (2026)
π let — modern, block-scoped, can be updated but not re-declared. Use when value changes
π’ const — modern, block-scoped, cannot be reassigned. Use as your default choice always
π΅ Scope — global, function, and block scope determine where a variable can be accessed
π©· Hoisting — var hoists with undefined; let/const hoist but stay in TDZ until declared
⭐ Golden Rule: Use const by default. Use let when value changes. Never use var.
When you are just starting out, the simplest rule to remember is: use const for everything first. If JavaScript gives you an error saying you are trying to change a constant, switch that specific variable to let. This approach naturally leads you to use const wherever possible and let only where necessary — which is exactly what professional JavaScript developers do every single day!
Comments
Post a Comment