JavaScript Variables: Complete Guide to var, let and const

Learn JavaScript Variables with this complete beginner-friendly guide. Understand var, let, const, scope, hoisting, data types, naming rules, examples, and best practices.

JavaScript Variables

JavaScript variables are containers used to store data that a program needs to work with. A variable can hold different types of values, such as text, numbers, Boolean values, objects, arrays, or even functions.

Variables are one of the most important building blocks of JavaScript. They allow developers to store information and use that information later in a program.

For example:

let name = "Dibya";
let age = 25;

Here, name stores the text "Dibya" and age stores the number 25.

JavaScript provides three main keywords for declaring variables:

  • var
  • let
  • const

Although all three can create variables, they behave differently. In modern JavaScript, let and const are generally preferred over var.


What Is a Variable in JavaScript?

A variable is a named reference that allows a program to work with a value.

Consider this example:

let city = "Bhubaneswar";

In this statement:

  • let declares the variable.
  • city is the variable name.
  • "Bhubaneswar" is the value.
  • = assigns the value to the variable.

The stored value can then be used elsewhere:

let city = "Bhubaneswar";

console.log(city);

Output:

Bhubaneswar

Variables make programs flexible because the stored values can be used in calculations, conditions, functions, loops, and many other operations.


Why Are Variables Important?

Variables are essential because programs frequently need to store and process information.

For example, an application might need to store:

  • A user’s name
  • Age
  • Email address
  • Product price
  • Shopping cart items
  • Login status
  • Game score
  • Website settings
  • API responses
  • Dates and times

Without variables, it would be difficult to create useful and interactive programs.

For example:

let productPrice = 500;
let quantity = 3;

let total = productPrice * quantity;

console.log(total);

Output:

1500

The variables allow the program to calculate the total dynamically.


Declaring JavaScript Variables

A variable can be declared using var, let, or const.

Using let

let name = "Rahul";

The value of a let variable can be changed later.

let score = 10;

score = 20;

console.log(score);

Output:

20

Using const

const country = "India";

A const variable cannot be reassigned after it has been initialized.

const country = "India";

country = "Japan";

This produces a TypeError.

Using var

var age = 25;

var is an older way of declaring variables. It is still supported by JavaScript, but modern code usually prefers let and const because their scoping behavior is safer and easier to understand.


let, const, and var Comparison

Featurevarletconst
Can be reassignedYesYesNo
Can be redeclared in same scopeYesNoNo
Block scopedNoYesYes
Function scopedYesYesYes
HoistedYesYes, but in TDZYes, but in TDZ
Must be initialized immediatelyNoNoYes
Recommended for modern codeUsually noYesYes

A simple rule is:

Use const by default. Use let when the value needs to change. Avoid var in new code unless you specifically need its older behavior.


JavaScript Variable Declaration and Assignment

Declaring a variable and assigning a value are related but different operations.

Declaration

let username;

The variable has been declared, but no explicit value has been assigned.

Its value is:

undefined

Assignment

username = "Amit";

Now the variable contains "Amit".

You can also declare and assign a variable in one statement:

let username = "Amit";


Multiple Variables

You can declare multiple variables separately:

let firstName = "Amit";
let lastName = "Kumar";
let age = 30;

You may also declare several variables in one statement:

let firstName = "Amit",
    lastName = "Kumar",
    age = 30;

Although this is valid JavaScript, separate declarations are often easier to read.


Variable Naming Rules

JavaScript has rules for naming variables.

A variable name:

  • Can contain letters.
  • Can contain digits.
  • Can contain _.
  • Can contain $.
  • Cannot begin with a digit.
  • Cannot contain spaces.
  • Is case-sensitive.
  • Cannot be a reserved JavaScript keyword.

Valid examples:

let name;
let userName;
let user_name;
let $price;
let price2;
let _count;

Invalid examples:

let 2name;
let user name;
let user-name;

The last example is interpreted as an expression involving the minus operator rather than a valid variable declaration.


JavaScript Variable Names Are Case-Sensitive

JavaScript treats uppercase and lowercase letters as different.

For example:

let name = "Amit";
let Name = "Rahul";

These are two different variables.

console.log(name);
console.log(Name);

Output:

Amit
Rahul

For this reason, consistent naming conventions are important.


JavaScript Reserved Words

Some words have special meanings in JavaScript and cannot normally be used as variable names.

Examples include:

let
const
var
if
else
for
while
function
return
class
new
this
switch
case
break
continue

For example:

let class = "JavaScript";

This is invalid because class is a reserved keyword.


Initializing Variables

Initialization means assigning an initial value to a variable.

let age = 25;

Here, age is initialized with 25.

With const, initialization is required:

const pi = 3.14159;

This is invalid:

const pi;

A const declaration must have an initializer.


Changing Variable Values

Variables declared with let can be reassigned.

let score = 50;

score = 75;

console.log(score);

Output:

75

The same applies to var:

var score = 50;
score = 75;

But a const binding cannot be reassigned:

const score = 50;
score = 75;

This results in an error.


const Does Not Make Objects Immutable

An important point about const is that it prevents reassignment of the variable binding. It does not automatically make objects or arrays immutable.

For example:

const person = {
    name: "Amit",
    age: 25
};

person.age = 26;

console.log(person.age);

Output:

26

The object itself can still be modified.

However, this is not allowed:

person = {
    name: "Rahul"
};

The variable cannot be reassigned to another object.


const and Arrays

The same rule applies to arrays.

const fruits = ["Apple", "Banana"];

fruits.push("Mango");

console.log(fruits);

Output:

["Apple", "Banana", "Mango"]

But this is not allowed:

fruits = ["Orange"];

So, const means the variable binding cannot be reassigned. It does not mean every value reachable through that binding is automatically frozen.

If you need an object or array to be non-extensible or frozen, JavaScript provides tools such as:

Object.freeze()


Variable Scope in JavaScript

Scope determines where a variable can be accessed.

JavaScript has several important types of scope:

  • Global scope
  • Module scope
  • Function scope
  • Block scope

Understanding scope is essential for writing reliable JavaScript programs.


Global Scope

A variable declared at the top level of a classic browser script can have global scope.

For example:

let siteName = "Example";

function showSite() {
    console.log(siteName);
}

showSite();

The function can access siteName because it is available in the surrounding scope.

However, global variables should be used carefully. Too many global variables can make programs harder to maintain and can cause naming conflicts.


Function Scope

Variables declared with var are function-scoped.

function test() {
    var message = "Hello";

    console.log(message);
}

test();

The variable is available inside the function.

But it cannot normally be accessed outside:

function test() {
    var message = "Hello";
}

console.log(message);

This causes a ReferenceError.


Block Scope

let and const are block-scoped.

A block is commonly represented by curly braces {}.

if (true) {
    let message = "Hello";
    const number = 10;

    console.log(message);
}

The variables are available inside the block.

They cannot be accessed outside it:

if (true) {
    let message = "Hello";
}

console.log(message);

This produces a ReferenceError.


Understanding Scope with var

The difference between var and let becomes clear with blocks.

if (true) {
    var x = 10;
}

console.log(x);

Output:

10

Because var is not block-scoped.

Compare that with:

if (true) {
    let y = 10;
}

console.log(y);

This results in a ReferenceError because y exists only inside the block.


The Temporal Dead Zone

Variables declared with let and const are hoisted, but they cannot be accessed before their declaration is evaluated.

The period between entering the scope and reaching the declaration is called the Temporal Dead Zone, or TDZ.

For example:

console.log(name);

let name = "Amit";

This results in a ReferenceError.

The same applies to const:

console.log(age);

const age = 25;

This also produces a ReferenceError.

Understanding the TDZ helps explain why let and const behave differently from older var declarations.


Variable Hoisting

JavaScript processes declarations before executing code within their scope. This behavior is commonly described as hoisting.

Consider:

console.log(value);

var value = 10;

The declaration of value is hoisted, and before the assignment happens its value is undefined.

Output:

undefined

With let and const, accessing the variable before its declaration results in a ReferenceError because of the Temporal Dead Zone.

It is therefore best practice to declare variables before using them.


var Redeclaration

One unusual feature of var is that the same variable can be redeclared in the same scope.

var name = "Amit";
var name = "Rahul";

console.log(name);

Output:

Rahul

With let, this is not allowed:

let name = "Amit";
let name = "Rahul";

This causes a SyntaxError.

The same applies to const.

This is one reason let and const can help prevent accidental redeclarations.


Variable Data Types

JavaScript variables can store values of different types.

String

let name = "Amit";

A string represents text.

Number

let age = 25;
let price = 99.99;

JavaScript uses the number type for both integers and floating-point numbers.

BigInt

let largeNumber = 9007199254740993n;

BigInt is used for integers that are outside the safe integer range of the regular Number type.

Boolean

let isLoggedIn = true;

A Boolean has either true or false as its value.

Undefined

let result;

A declared variable without an assigned value normally contains undefined.

Null

let selectedItem = null;

null is commonly used to represent an intentional absence of a value.

Object

let person = {
    name: "Amit",
    age: 25
};

Array

let colors = ["Red", "Green", "Blue"];

Arrays are objects in JavaScript and are used to store ordered collections.

Function

Functions can also be stored in variables:

const greet = function () {
    console.log("Hello");
};

Modern JavaScript also commonly uses arrow functions:

const greet = () => {
    console.log("Hello");
};


JavaScript Variables Are Dynamically Typed

JavaScript is dynamically typed. A variable does not need a type declaration such as int, string, or boolean.

For example:

let value = 100;

Later, the same variable can hold a string:

value = "Hello";

This is valid JavaScript.

However, changing the kind of value stored in a variable unnecessarily can make code harder to understand. Clear and consistent variable usage is usually better.


Using typeof with Variables

The typeof operator can be used to determine the type of a value.

let name = "Amit";
let age = 25;
let active = true;

console.log(typeof name);
console.log(typeof age);
console.log(typeof active);

Output:

string
number
boolean

For an object:

const person = {};
console.log(typeof person);

Output:

object

One historical JavaScript quirk is:

typeof null

which returns:

object

Although null is a primitive value, this behavior is retained for compatibility with existing JavaScript programs.


Variables and Expressions

Variables can be used in expressions.

let a = 10;
let b = 20;

let sum = a + b;

console.log(sum);

Output:

30

Expressions can contain variables, operators, function calls, and values.


Variables in Mathematical Calculations

Variables make calculations dynamic.

let price = 1000;
let discount = 100;

let finalPrice = price - discount;

console.log(finalPrice);

Output:

900

Another example:

let length = 10;
let width = 5;

let area = length * width;

console.log(area);

Output:

50


Variables and Strings

Variables can store and combine strings.

let firstName = "Dibya";
let lastName = "Mendali";

let fullName = firstName + " " + lastName;

console.log(fullName);

Output:

Dibya Mendali

Template literals provide a cleaner approach:

let firstName = "Dibya";
let lastName = "Mendali";

let fullName = `${firstName} ${lastName}`;

console.log(fullName);


Variables in Conditions

Variables are frequently used in if statements.

let age = 20;

if (age >= 18) {
    console.log("You are an adult.");
}

The program checks the value stored in age and then decides what to do.


Variables in Loops

Variables are also important in loops.

for (let i = 1; i <= 5; i++) {
    console.log(i);
}

Here, i is used to keep track of the current iteration.

Because i is declared with let, it is scoped to the loop structure.


Variables and Functions

Variables can be passed to functions.

function greet(name) {
    console.log("Hello " + name);
}

let username = "Amit";

greet(username);

Output:

Hello Amit

Functions can also return values that are stored in variables:

function add(a, b) {
    return a + b;
}

const result = add(10, 20);

console.log(result);

Output:

30


Destructuring Assignment

JavaScript allows values to be extracted from arrays and objects using destructuring.

Array Destructuring

const numbers = [10, 20, 30];

const [first, second, third] = numbers;

console.log(first);
console.log(second);
console.log(third);

Output:

10
20
30

Object Destructuring

const person = {
    name: "Amit",
    age: 25
};

const { name, age } = person;

console.log(name);
console.log(age);

Destructuring can make code shorter and easier to read when working with objects and arrays.


Variable Naming Conventions

JavaScript developers commonly use camelCase for variable names.

Examples:

let firstName;
let lastName;
let totalPrice;
let userAge;
let accountBalance;

Avoid unclear names such as:

let x;
let y;
let z;

unless the purpose is obvious, such as a mathematical calculation or a short loop.

A descriptive name makes code easier to understand.

For example:

let totalShoppingCartPrice = 2500;

is more informative than:

let x = 2500;


Constants and Naming Conventions

For normal JavaScript variables, camelCase is common:

const userName = "Amit";

For constants whose values represent fixed configuration or application-wide values, some codebases use uppercase names with underscores:

const MAX_USERS = 100;
const API_TIMEOUT = 5000;

This is a convention rather than a JavaScript requirement.


Avoid Unnecessary Global Variables

Global variables can be accessed from many parts of a program. This can make debugging difficult and may create accidental conflicts.

Instead of:

let total = 0;

function calculate() {
    total = 100;
}

it is often better to keep values close to where they are needed:

function calculate() {
    const total = 100;
    return total;
}

Smaller scopes generally make programs easier to understand and maintain.


Best Practices for JavaScript Variables

Prefer const

Use const when you do not need to reassign the variable.

const name = "Amit";

Use let for changing values

let score = 0;

score += 10;

Avoid var in new code

Modern JavaScript usually favors let and const because they provide block scope and avoid several common problems associated with var.

Use meaningful names

Prefer:

const customerName = "Amit";

instead of:

const x = "Amit";

Declare variables before using them

This makes the code easier to read and avoids confusing behavior related to hoisting and the Temporal Dead Zone.

Keep variables in the smallest useful scope

Do not make a variable global if it only needs to be used inside a function or block.

Avoid unnecessary reassignment

If a value never needs to change, use const.


Common Mistakes with JavaScript Variables

Mistake 1: Trying to Reassign a const

const age = 25;

age = 30;

This is not allowed.

Use let if the value must change:

let age = 25;
age = 30;

Mistake 2: Accessing let Before Declaration

console.log(name);

let name = "Amit";

This causes a ReferenceError.

Declare the variable before using it.

Mistake 3: Using Invalid Variable Names

let 123name = "Amit";

A variable name cannot begin with a digit.

Use:

let name123 = "Amit";

Mistake 4: Confusing = and ==

The = operator is used for assignment:

let age = 25;

The == operator performs loose equality comparison:

age == 25

The === operator performs strict equality comparison:

age === 25

In modern JavaScript, === is generally preferred for equality comparisons because it avoids implicit type conversion in the comparison.

Mistake 5: Assuming const Makes Objects Immutable

This is valid:

const user = {
    name: "Amit"
};

user.name = "Rahul";

const prevents reassignment of user, not modification of the object’s properties.


JavaScript Variables in Strict Mode

Strict mode can help identify certain programming mistakes.

You can enable it with:

"use strict";

Modern JavaScript modules are automatically strict mode code.

Strict mode changes or restricts some older JavaScript behaviors and can make certain errors easier to detect.

For example, assigning to an undeclared variable is an error in strict mode:

"use strict";

username = "Amit";

The variable should instead be declared:

let username = "Amit";


Variables in JavaScript Modules

JavaScript modules have their own top-level scope.

For example:

const appName = "My App";

export { appName };

Another module can import it:

import { appName } from "./app.js";

console.log(appName);

Module scope helps prevent unrelated scripts from accidentally sharing or overwriting variables.


Variable Lifetime

A variable exists according to the scope and execution context in which it is created.

For example:

function test() {
    let message = "Hello";
    console.log(message);
}

The variable message belongs to the function’s scope.

When the relevant execution context is no longer needed, JavaScript’s garbage collector can reclaim memory that is no longer reachable.

Developers normally do not manually free ordinary JavaScript variables.


JavaScript Variables and Memory

Variables hold or reference values.

For primitive values such as:

let age = 25;

the variable contains a primitive value.

For objects:

const user = {
    name: "Amit"
};

the variable holds a reference to an object.

This distinction becomes important when assigning objects to multiple variables:

const user1 = {
    name: "Amit"
};

const user2 = user1;

user2.name = "Rahul";

console.log(user1.name);

Output:

Rahul

Both variables refer to the same object.


Primitive Values and Variables

JavaScript has seven primitive data types:

  • String
  • Number
  • BigInt
  • Boolean
  • Undefined
  • Null
  • Symbol

For example:

const name = "Amit";
const age = 25;
const largeValue = 10000000000000000n;
const active = true;
const result = undefined;
const selected = null;
const id = Symbol("id");

Objects, arrays, and functions are not primitive values.


Symbol Variables

A Symbol creates a unique primitive value.

const id = Symbol("id");

Two symbols with the same description are still different:

const a = Symbol("id");
const b = Symbol("id");

console.log(a === b);

Output:

false

Symbols are often used as unique property keys.


BigInt Variables

BigInt allows JavaScript to represent integers larger than the safe range of Number.

const population = 9007199254740993n;

console.log(population);

The n at the end identifies a BigInt literal.

BigInt and Number should not normally be mixed directly in arithmetic:

const a = 10n;
const b = 5;

console.log(a + b);

This results in a TypeError.

Convert values explicitly when appropriate.


Null and Undefined Variables

Although null and undefined are both associated with missing values, they have different meanings.

undefined commonly indicates that a value has not been assigned:

let value;
console.log(value);

Output:

undefined

null is often used when you intentionally want to indicate that there is no value:

let selectedUser = null;

The exact meaning depends on the program’s design.


Variable Declaration Without Initialization

let can be declared without an initial value:

let username;

Later:

username = "Amit";

This is valid.

const cannot be declared this way:

const username;

It produces a syntax error because a constant binding must be initialized when declared.


Chained Assignment

JavaScript allows chained assignment:

let a, b, c;

a = b = c = 10;

All three variables receive 10.

Although valid, this style can sometimes make code harder to read. Separate assignments are often clearer when the values or intent are more complex.


Swapping Variable Values

Two variables can be swapped using array destructuring:

let a = 10;
let b = 20;

[a, b] = [b, a];

console.log(a);
console.log(b);

Output:

20
10

This is a convenient modern JavaScript technique.


Variables with Default Values

Destructuring can also provide default values.

const [first = "Unknown"] = [];

Now:

console.log(first);

Output:

Unknown

Object destructuring supports defaults as well:

const { name = "Guest" } = {};


Variables and the Nullish Coalescing Operator

The ?? operator can provide a fallback when a value is null or undefined.

const username = null;

const displayName = username ?? "Guest";

console.log(displayName);

Output:

Guest

This is useful when handling optional data.


Variables and Optional Chaining

Optional chaining can safely access properties that may not exist.

const user = {};

const city = user.address?.city;

console.log(city);

Output:

undefined

This can help prevent errors when working with nested data.


JavaScript Variables in Real-World Applications

Variables are used throughout modern web applications.

For example, an online shopping application may have:

const productName = "Laptop";
const productPrice = 55000;
let quantity = 2;
const isAvailable = true;

A banking application might use:

const accountNumber = "XXXXXX";
let balance = 25000;
const currency = "INR";

A game might use:

let score = 0;
let lives = 3;
const level = 1;

A website form might use:

let userName = "";
let email = "";
let message = "";

Variables allow the application to respond to user actions and changing data.


A Practical Example

Here is a simple example that combines variables, calculations, conditions, and output:

const productName = "Mobile Phone";
const price = 20000;
const quantity = 2;
const discount = 1000;

const subtotal = price * quantity;
const total = subtotal - discount;

console.log("Product:", productName);
console.log("Subtotal:", subtotal);
console.log("Discount:", discount);
console.log("Total:", total);

Output:

Product: Mobile Phone
Subtotal: 40000
Discount: 1000
Total: 39000

This demonstrates why variables are so useful. Each piece of information can be stored, reused, and combined to produce the final result.


var vs let vs const Example

Consider the following:

var oldStyle = "var";

let changingValue = "first";
changingValue = "second";

const fixedValue = "constant";

Here:

  • oldStyle uses the older var declaration.
  • changingValue can be reassigned.
  • fixedValue cannot be reassigned.

For most modern JavaScript applications, this pattern is recommended:

const fixedValue = "Hello";
let changingValue = 10;


Frequently Asked Questions

What is a variable in JavaScript?

A variable is a named binding used by a JavaScript program to store or refer to a value.

What are the three ways to declare variables in JavaScript?

JavaScript provides var, let, and const.

Which variable declaration should I use?

Use const when you do not need to reassign the variable. Use let when the value needs to change. In modern JavaScript, var is generally avoided in new code.

Can a const variable be changed?

A const variable cannot be reassigned. However, if it refers to an object or array, the object’s contents can still be changed unless the object is otherwise made immutable.

Can let be redeclared?

No. You cannot redeclare a let variable in the same scope.

Can var be redeclared?

Yes. var permits redeclaration within the same scope.

Are JavaScript variables case-sensitive?

Yes. name, Name, and NAME are different identifiers.

Can a JavaScript variable start with a number?

No. A variable name cannot start with a digit.

Can a JavaScript variable contain $?

Yes.

let $price = 100;

This is valid JavaScript.

Can a JavaScript variable contain _?

Yes.

let _count = 10;

This is valid.

What is the default value of an uninitialized let variable?

It is undefined.

let value;
console.log(value);

const makes it clear that a variable binding should not be reassigned. This reduces accidental changes and makes code easier to reason about.

What is variable scope?

Scope defines where a variable can be accessed in a program.

What is the difference between let and var?

let is block-scoped, while var is function-scoped. let also cannot be redeclared in the same scope.

What happens when a variable is accessed before its let declaration?

JavaScript throws a ReferenceError because the variable is in the Temporal Dead Zone.

Are JavaScript variables statically typed?

No. JavaScript is dynamically typed, so a variable can hold different kinds of values during its lifetime.


Key Points to Remember

JavaScript variables are fundamental to programming because they allow programs to store and work with data.

The most important points are:

  • JavaScript provides var, let, and const.
  • Prefer const when reassignment is not needed.
  • Use let when a variable must be reassigned.
  • Avoid var in most new JavaScript code.
  • let and const are block-scoped.
  • var is function-scoped.
  • JavaScript variable names are case-sensitive.
  • Variable names cannot start with numbers.
  • Variables can store many different types of values.
  • JavaScript is dynamically typed.
  • const prevents reassignment of a binding, but does not automatically freeze objects or arrays.
  • let and const have Temporal Dead Zones.
  • Meaningful variable names make code easier to read.
  • Keeping variables in the smallest useful scope improves maintainability.

Conclusion

JavaScript variables are one of the basic concepts that every JavaScript developer should understand. They provide a way to store, access, update, and work with information throughout a program.

The three declaration keywords—var, let, and const—have different behavior. In modern JavaScript, const is usually the best starting choice, while let should be used when reassignment is required. Although var remains part of the language, its function-scoped behavior makes it less suitable for most new code.

Once you understand variable declaration, assignment, scope, hoisting, the Temporal Dead Zone, data types, and naming conventions, many other JavaScript concepts become easier to learn.

A strong understanding of variables provides the foundation for learning more advanced JavaScript topics such as functions, objects, arrays, loops, classes, modules, asynchronous programming, and modern web development.

Scroll to Top