DocsHub
Basics

JavaScript Variables

Learn how to store and manage data in JavaScript using var, let, and const.

JavaScript Variables

A variable is a named container for storing data.

Think of it like a labeled box. You put something inside it, give the box a name, and whenever you need that thing — you just call its name.

let username = "Ali";
console.log(username); // Ali

That's it. username is the box. "Ali" is what's inside it.


How to Create a Variable

JavaScript has three keywords for creating variables:

KeywordIntroducedUse today?
var1995 (original)❌ Avoid
letES6 (2015)✅ Yes
constES6 (2015)✅ Yes

You'll see var in old code. Modern JavaScript uses let and const — and for good reason.


let — A Variable That Can Change

Use let when the value of a variable will change over time.

let score = 0;
console.log(score); // 0

score = 10;
console.log(score); // 10

score = score + 5;
console.log(score); // 15

You declared it once with let, and updated it freely after that.


const — A Variable That Cannot Change

Use const when the value should never be reassigned.

const PI = 3.14159;
console.log(PI); // 3.14159

PI = 3; // ❌ TypeError: Assignment to constant variable

Once you set it, it's locked. Trying to reassign it throws an error.

const siteName = "DocsHub";
const maxScore = 100;
const isLoggedIn = true;

These values don't need to change — so const is the right choice.

Rule of thumb: Always start with const. Only switch to let if you know the value will need to change. This keeps your code predictable.


var — The Old Way (And Why It Was Abandoned)

var was the only way to declare variables before 2015. It works — but it has two serious problems that caused real bugs in real applications.

Problem 1 — var ignores block boundaries

In JavaScript, a block is any code inside { } — like an if statement or a loop.

let and const respect blocks. var does not.

// Using let — behaves as expected
if (true) {
  let message = "Hello";
}
console.log(message); // ❌ ReferenceError: message is not defined
// Using var — leaks outside the block
if (true) {
  var message = "Hello";
}
console.log(message); // ✅ "Hello" — but this is a bug, not a feature

The var version works — but that's the problem. message escaped the if block and is now accessible everywhere. This leads to accidental overwrites and confusing code.

Problem 2 — var gets hoisted and becomes undefined

JavaScript moves var declarations to the top of their scope before running the code. This is called hoisting.

console.log(age); // undefined (no error, but wrong)
var age = 25;
console.log(age); // 25

JavaScript silently rewrites this as:

var age;            // moved to top
console.log(age);  // undefined
age = 25;
console.log(age);  // 25

Using a variable before you define it should be an error. With var, it's not — it just silently returns undefined, which hides bugs instead of exposing them.

let and const fix this:

console.log(age); // ❌ ReferenceError: Cannot access 'age' before initialization
let age = 25;

A clear error is better than silent wrong behavior.


Side-by-Side Comparison

// ✅ const — value never changes
const country = "Pakistan";

// ✅ let — value changes over time
let lives = 3;
lives = lives - 1;

// ❌ var — avoid this
var name = "Ali";
Featurevarletconst
Can be reassigned
Block scoped
Hoisted safely
Use today

Naming Variables

Variable names in JavaScript follow these rules:

// ✅ Valid names
let userName = "Ali";
let score2 = 99;
let _private = true;
let $price = 50;

// ❌ Invalid names
let 2score = 99;     // cannot start with a number
let my-score = 99;   // hyphens not allowed
let let = "value";   // reserved keyword

Use camelCase for variable names — it's the JavaScript convention:

// ✅ camelCase (JavaScript standard)
let firstName = "Ali";
let totalScore = 0;
let isGameOver = false;

// ❌ Not conventional in JS
let first_name = "Ali";   // snake_case (Python style)
let FirstName = "Ali";    // PascalCase (reserved for classes)

A Real Example

const playerName = "Ali";   // never changes
let health = 100;            // changes during the game
let level = 1;               // changes as player progresses

console.log(`${playerName} starts at level ${level} with ${health} HP.`);
// Ali starts at level 1 with 100 HP.

health = health - 20;        // player took damage
level = level + 1;           // player leveled up

console.log(`${playerName} is now level ${level} with ${health} HP.`);
// Ali is now level 2 with 80 HP.

playerName is const because the player's name never changes. health and level are let because they change as the game progresses. Simple and intentional.


Summary

  • A variable is a named box that stores a value
  • Use const by default — when the value won't change
  • Use let when the value needs to be updated
  • Avoid var — it has scoping and hoisting problems that cause bugs
  • Name your variables in camelCase and make them descriptive

On this page