LearnContact
Lesson 540 min read

JavaScript Variables

Learn how JavaScript variables store and manage data using var, let, and const, including declaration, initialization, reassignment, naming rules, scope basics, and best practices.

Introduction

Almost every useful JavaScript program needs to store information. A shopping website stores product prices, a game stores the player score, a login form stores the entered username, and a weather application stores temperature data.

JavaScript uses variables to store and manage these values. Variables allow programs to remember information, update it when necessary, and use it later during execution.

JavaScript provides three keywords for creating variables: var, let, and const. Although all three can store values, they behave differently and are used for different purposes.

What You Will Learn
  • What a variable is.
  • Why programs need variables.
  • How to declare and initialize variables.
  • The difference between declaration, assignment, and reassignment.
  • How var, let, and const work.
  • The differences between var, let, and const.
  • Rules for naming variables.
  • How JavaScript stores different types of values.
  • What dynamic typing means.
  • How variable scope works at a basic level.
  • How const behaves with arrays and objects.
  • Common mistakes and modern best practices.

What is a Variable?

A variable is a named container used to store a value in a program.

Instead of repeatedly writing the same value directly in the code, we can store that value inside a variable and refer to it using a meaningful name.

Simple Variable
let age = 25;

console.log(age);
Output

In this example, age is the variable name and 25 is the value stored in the variable.

Variable Structure
let age = 25;
│   │     │
│   │     └── Value
│   │
│   └── Variable Name
│
└── Declaration Keyword
Simple Definition
  • A variable has a name.
  • A variable can store a value.
  • The stored value can be used later.
  • Some variables can receive a new value during program execution.

Why Do We Need Variables?

Without variables, programs would have difficulty remembering and reusing information. Variables make code dynamic, readable, reusable, and easier to maintain.

Store Data

Variables store information such as names, prices, scores, and settings.

Reuse Values

A stored value can be used multiple times without rewriting it.

Update Information

Values such as scores, quantities, and counters can change while a program runs.

Perform Calculations

Variables can participate in mathematical expressions and calculations.

Improve Readability

Meaningful variable names explain what values represent.

Build Dynamic Programs

Variables allow applications to respond to users and changing data.

Without Variables
console.log(500 * 3);
console.log((500 * 3) + 100);
With Variables
const price = 500;
const quantity = 3;
const deliveryCharge = 100;

const total = price * quantity;
const finalAmount = total + deliveryCharge;

console.log(total);
console.log(finalAmount);
Output

The second example clearly explains what each number represents and makes future changes easier.

Real-World Analogy

Think of a variable as a labeled storage box. The label identifies the box, and the box contains a value.

Storage Box Analogy
┌──────────────────────┐
│ Label: studentName   │
│                      │
│ Value: "Rahul"       │
└──────────────────────┘

┌──────────────────────┐
│ Label: age           │
│                      │
│ Value: 22            │
└──────────────────────┘

┌──────────────────────┐
│ Label: isActive      │
│                      │
│ Value: true          │
└──────────────────────┘

When the program needs a value, it uses the variable name to access the stored information.

Variable Name

Works like the label attached to a storage box.

Stored Value

Represents the information placed inside the box.

Accessing

Using the variable name retrieves the stored value.

Reassignment

For changeable variables, the old value can be replaced with a new one.

Variable Declaration

Declaration means creating a variable and giving it a name.

Variable Declaration
let username;

The variable username has been declared, but no value has been explicitly assigned to it.

Checking the Variable
let username;

console.log(username);
Output

Because no value has been assigned, the variable currently contains the special value undefined.

Variable Initialization

Initialization means giving a variable its first value.

Declaration and Initialization
let username = 'Rahul';

console.log(username);
Output
Initialization
let username = 'Rahul';
│       │        │
│       │        └── Initial Value
│       │
│       └── Variable Name
│
└── Declaration Keyword

Declaration vs Initialization

Declaration and initialization are related, but they are not the same operation.

Separate Declaration and Initialization
// Declaration
let city;

// Initialization
city = 'Mumbai';

console.log(city);
Output
Declaration and Initialization Together
let city = 'Mumbai';

console.log(city);
Output

Declaration

Creates the variable name.

Initialization

Provides the variable with its first value.

Variable Assignment

Assignment means storing a value in a variable using the assignment operator (=).

Assignment
let score;

score = 100;

console.log(score);
Output
The = Symbol Does Not Mean Mathematical Equality
  • In JavaScript, = is the assignment operator.
  • It takes the value on the right.
  • It stores that value in the variable on the left.
  • Comparison operators are explained in the Operators lesson.

Variable Reassignment

Reassignment means replacing the current value of an existing variable with a new value.

Reassigning a Variable
let score = 10;

console.log(score);

score = 20;

console.log(score);
Output
Value Change
Initial Value

score → 10

After Reassignment

score → 20

The variable name remains the same, but the stored value changes.

JavaScript Variable Keywords

JavaScript provides three keywords for declaring variables.

var

The original variable declaration keyword. It has function scope and older behavior.

let

A modern keyword used for values that may need reassignment.

const

A modern keyword used when the variable binding should not be reassigned.

Three Variable Keywords
var oldStyle = 'JavaScript';

let currentScore = 10;

const courseName = 'Core JavaScript';

The var Keyword

The var keyword was the original way to declare variables in JavaScript.

Using var
var language = 'JavaScript';

console.log(language);
Output

A variable declared with var can be reassigned.

Reassigning var
var score = 10;

score = 20;

console.log(score);
Output

A var variable can also be redeclared in the same scope.

Redeclaring var
var city = 'Mumbai';
var city = 'Pune';

console.log(city);
Output
Why var is Usually Avoided in Modern JavaScript
  • var can be redeclared in the same scope.
  • var is function-scoped rather than block-scoped.
  • Its hoisting behavior can confuse beginners.
  • let and const usually make code behavior clearer.
  • You will still see var in older JavaScript projects.

The let Keyword

The let keyword is used to create variables whose values may need to change later.

Using let
let score = 10;

console.log(score);

score = 25;

console.log(score);
Output

A let variable can be reassigned, but it cannot be redeclared in the same scope.

Invalid Redeclaration
let username = 'Rahul';

let username = 'Amit';
Result
When to Use let
  • Counters that change.
  • Scores that update.
  • Current user selections.
  • Values that are intentionally reassigned.
  • Loop variables.
Practical let Example
let cartQuantity = 1;

cartQuantity = 2;
cartQuantity = 3;

console.log(cartQuantity);
Output

The const Keyword

The const keyword creates a variable binding that cannot be reassigned after initialization.

Using const
const courseName = 'Core JavaScript';

console.log(courseName);
Output

Attempting to assign a new value to the same const variable causes an error.

Invalid const Reassignment
const courseName = 'Core JavaScript';

courseName = 'Advanced JavaScript';
Result

A const variable must also receive a value when it is declared.

Invalid const Declaration
const price;
Result
When to Use const
  • Values that should not be reassigned.
  • Configuration values.
  • Function references.
  • Arrays and objects whose variable binding should remain the same.
  • Most variables by default in modern JavaScript.

var vs let vs const

The three variable keywords differ in reassignment, redeclaration, scope, and modern usage.

Comparison
Feature              var        let        const
------------------------------------------------------
Can Reassign?         Yes        Yes        No
Can Redeclare?        Yes        No         No
Block Scoped?         No         Yes        Yes
Function Scoped?      Yes        No*        No*
Must Initialize?      No         No         Yes
Modern Usage?         Rare       Yes        Yes

* let and const can exist inside function scope,
  but their defining feature is block scope.
Modern Recommendation
  • Use const by default.
  • Use let when reassignment is required.
  • Avoid var in new JavaScript code unless you specifically need its behavior.
Recommended Style
const courseName = 'JavaScript';

let currentLesson = 5;

currentLesson = 6;

Variable Naming Rules

JavaScript variable names must follow specific syntax rules.

  • A variable name can contain letters.
  • A variable name can contain digits.
  • A variable name can contain an underscore (_).
  • A variable name can contain a dollar sign ($).
  • A variable name cannot begin with a digit.
  • A variable name cannot contain spaces.
  • A variable name cannot contain most special characters.
  • A reserved JavaScript keyword cannot be used as a variable name.
  • Variable names are case-sensitive.
Basic Rule
Can Start With:

Letter       → name
Underscore   → _name
Dollar Sign  → $name

Cannot Start With:

Number       → 1name ❌

Valid Variable Names

Valid Names
let name = 'Rahul';
let userName = 'Amit';
let user1 = 'Priya';
let _score = 100;
let $price = 500;
let firstName = 'Riya';
let totalAmount = 1500;
All These Names are Valid
  • name
  • userName
  • user1
  • _score
  • $price
  • firstName
  • totalAmount

Invalid Variable Names

Invalid Names
// Starts with a number
let 1name = 'Rahul';

// Contains a space
let user name = 'Amit';

// Contains a hyphen
let user-name = 'Priya';

// Reserved keyword
let let = 10;
These Names are Invalid
  • 1name starts with a number.
  • user name contains a space.
  • user-name contains a hyphen.
  • let is a reserved JavaScript keyword.

JavaScript Variable Names are Case-Sensitive

JavaScript treats uppercase and lowercase letters as different characters.

Case Sensitivity
let name = 'Rahul';
let Name = 'Amit';
let NAME = 'Priya';

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

The names name, Name, and NAME represent three different variables.

Variable Naming Conventions

A naming convention is a consistent style used to create readable variable names. JavaScript developers commonly use camelCase.

camelCase
const firstName = 'Rahul';
const lastName = 'Sharma';
const totalPrice = 1500;
const isLoggedIn = true;
const numberOfStudents = 50;
camelCase Structure
firstName
│    │
│    └── Next Word Starts With Capital Letter
│
└── First Word Starts With Lowercase Letter
Use Meaningful Names
  • Use age instead of a.
  • Use productPrice instead of p.
  • Use totalAmount instead of x.
  • Use isLoggedIn instead of flag when the meaning is specific.
  • Choose names that explain the purpose of the stored value.
Poor vs Good Names
// Poor
let x = 500;
let y = 3;
let z = x * y;

// Better
const productPrice = 500;
const quantity = 3;
const totalPrice = productPrice * quantity;

Storing Different Data Types

JavaScript variables can store many different types of values.

Different Values
const courseName = 'JavaScript';
const lessonNumber = 5;
const isCompleted = false;
const emptyValue = null;
const topics = ['Variables', 'Constants', 'Data Types'];

const student = {
    name: 'Rahul',
    age: 22
};

console.log(courseName);
console.log(lessonNumber);
console.log(isCompleted);
console.log(emptyValue);
console.log(topics);
console.log(student);

String

Stores textual information.

Number

Stores numeric values.

Boolean

Stores true or false.

Null

Represents an intentional absence of value.

Array

Stores an ordered collection of values.

Object

Stores related information using properties.

Coming Next
  • Each JavaScript data type will be explained in detail in the Data Types lesson.
  • Arrays and Objects also have dedicated lessons later in this course.

Dynamic Typing

JavaScript is dynamically typed. This means you do not specify a fixed data type when declaring a variable.

Dynamic Typing
let value = 100;

console.log(value);

value = 'JavaScript';

console.log(value);

value = true;

console.log(value);
Output

The same let variable first stores a number, then a string, and finally a boolean.

Use Dynamic Typing Carefully
  • JavaScript allows a variable to receive values of different types.
  • Frequent unexpected type changes can make code difficult to understand.
  • Use clear names and predictable values whenever possible.

Declaring Multiple Variables

You can declare multiple variables separately or in a single declaration.

Separate Declarations
const firstName = 'Rahul';
const age = 22;
const city = 'Mumbai';
Single Declaration
let firstName = 'Rahul',
    age = 22,
    city = 'Mumbai';
Recommended for Beginners
  • Prefer one variable declaration per line.
  • Separate declarations are easier to read.
  • Separate declarations are easier to modify and debug.

Copying Variable Values

The value of one variable can be assigned to another variable.

Copying a Primitive Value
let originalScore = 100;
let copiedScore = originalScore;

console.log(originalScore);
console.log(copiedScore);
Output
Changing the Original
let originalScore = 100;
let copiedScore = originalScore;

originalScore = 200;

console.log(originalScore);
console.log(copiedScore);
Output

For primitive values such as numbers, the value is copied. Changing the original variable does not change the copied variable.

Objects Behave Differently
  • Objects and arrays involve reference behavior.
  • That behavior will be explained in the Objects and Arrays lessons.

Using Variables in Expressions

Variables can be combined with operators to perform calculations and create new values.

Price Calculation
const productPrice = 500;
const quantity = 3;

const totalPrice = productPrice * quantity;

console.log(totalPrice);
Output
Student Marks
const mathematics = 85;
const science = 90;
const english = 80;

const total = mathematics + science + english;
const average = total / 3;

console.log('Total:', total);
console.log('Average:', average);
Output

Using Variables in Strings

Variables are frequently combined with text to create dynamic messages.

String Concatenation
const name = 'Rahul';
const age = 22;

const message = 'My name is ' + name + ' and I am ' + age + ' years old.';

console.log(message);
Output

Modern JavaScript also provides template literals, which make dynamic strings easier to write.

Template Literal
const name = 'Rahul';
const age = 22;

const message = `My name is ${name} and I am ${age} years old.`;

console.log(message);
Output
Template Literals
  • Template literals use backticks (`).
  • Variables are inserted using ${variableName}.
  • They will be covered in greater detail in the Strings lesson.

Undefined Variables

A declared variable that has not yet received an explicit value contains undefined.

Undefined Variable
let username;

console.log(username);
Output
Variable State
Declared

username
    ↓
No Explicit Value Assigned
    ↓
undefined

Undeclared Variables

An undeclared variable is a variable name that has not been declared using var, let, or const in an accessible scope.

Undeclared Variable
console.log(username);
Result
undefined vs Not Defined
  • A declared variable without an assigned value can contain undefined.
  • An inaccessible or undeclared variable name can produce a ReferenceError.
  • These situations are different.

Variable Scope Basics

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

JavaScript variables can exist in different scopes depending on where and how they are declared.

Global Scope

The variable is declared outside functions and blocks.

Function Scope

The variable exists inside a particular function.

Block Scope

The variable exists inside a block such as an if statement or loop.

Dedicated Scope Lesson
  • This section introduces only the basic idea of scope.
  • Scope will be explained in complete detail in Lesson 14.

Global Variables

A variable declared at the top level of a script is available to code in its accessible global scope.

Global Variable
const courseName = 'JavaScript';

function showCourse() {
    console.log(courseName);
}

showCourse();

console.log(courseName);
Output

The function can access courseName because the variable was declared outside the function.

Function Variables

Variables declared inside a function are local to that function or to a more specific scope inside it.

Function Variable
function greet() {
    const message = 'Hello from JavaScript';

    console.log(message);
}

greet();
Output
Accessing Outside the Function
function greet() {
    const message = 'Hello';
}

console.log(message);
Result

Block Variables

Variables declared with let and const are block-scoped. A block is commonly represented by curly braces.

Block Scope
if (true) {
    let score = 100;
    const message = 'Completed';

    console.log(score);
    console.log(message);
}
Output
Outside the Block
if (true) {
    let score = 100;
}

console.log(score);
Result

The score variable exists only inside the block where it was declared.

Variable Shadowing

Variable shadowing occurs when an inner scope declares a variable with the same name as a variable in an outer scope.

Variable Shadowing
const message = 'Global Message';

function showMessage() {
    const message = 'Local Message';

    console.log(message);
}

showMessage();

console.log(message);
Output
Shadowing
Global Scope
│
└── message = 'Global Message'
        │
        └── Function Scope
            │
            └── message = 'Local Message'
                ↑
                This inner variable is used
                inside the function

The inner message variable temporarily hides the outer message variable inside the function.

const with Arrays and Objects

A common beginner misunderstanding is that const makes every part of a value completely unchangeable.

For arrays and objects, const prevents reassignment of the variable binding. It does not automatically make the contents of the array or object immutable.

const Array
const technologies = ['HTML', 'CSS'];

technologies.push('JavaScript');

console.log(technologies);
Output
const Object
const user = {
    name: 'Rahul',
    age: 22
};

user.age = 23;

console.log(user);
Output

The contents can be modified, but the variable cannot be reassigned to a completely different array or object.

Invalid Reassignment
const technologies = ['HTML', 'CSS'];

technologies = ['JavaScript', 'React'];
Result
Remember
  • const prevents reassignment of the variable.
  • It does not automatically freeze an array.
  • It does not automatically freeze an object.
  • Array elements and object properties can still be modified.
  • Objects and arrays will be explained fully in later lessons.

Variables in Memory

When a variable is created, JavaScript manages the memory required to store and access its value.

Variables
const course = 'JavaScript';
let lesson = 5;
let completed = false;
Simplified Memory View
Variable        Value
----------------------------
course      →   'JavaScript'
lesson      →   5
completed   →   false

When a changeable variable is reassigned, JavaScript updates the value associated with that variable according to the language and runtime memory model.

Reassignment
let lesson = 5;

lesson = 6;
Simplified Change
Before

lesson → 5

After

lesson → 6
Simplified Model
  • This storage-box model is useful for learning variables.
  • Actual JavaScript memory management is more complex.
  • Primitive values and reference values behave differently.
  • Those differences will be explored in later lessons.

Complete Variable Example

The following example combines constants, changeable variables, calculations, reassignment, and dynamic output.

shopping-cart.js
const productName = 'Wireless Mouse';
const productPrice = 750;

let quantity = 2;

let totalPrice = productPrice * quantity;

console.log('Product:', productName);
console.log('Price:', productPrice);
console.log('Quantity:', quantity);
console.log('Total:', totalPrice);

// Customer changes the quantity
quantity = 3;

totalPrice = productPrice * quantity;

console.log('Updated Quantity:', quantity);
console.log('Updated Total:', totalPrice);
Output
Execution Flow
productName = 'Wireless Mouse'
          ↓
productPrice = 750
          ↓
quantity = 2
          ↓
totalPrice = 750 × 2
          ↓
totalPrice = 1500
          ↓
Display Initial Details
          ↓
quantity Changes to 3
          ↓
totalPrice = 750 × 3
          ↓
totalPrice = 2250
          ↓
Display Updated Details

Real-World Applications

Variables are used in almost every part of modern software development.

Shopping Cart

Store product prices, quantities, discounts, and totals.

Games

Store scores, player health, levels, and game state.

User Profiles

Store names, ages, preferences, and account information.

Weather Apps

Store temperature, humidity, city, and forecast information.

Dashboards

Store statistics, filters, totals, and selected data.

Forms

Store values entered by users.

Authentication

Track login state and user information.

Application Settings

Store themes, language preferences, and configuration.

Common Beginner Mistakes

Avoid These Mistakes
  • Using a variable before understanding whether it has been declared.
  • Confusing declaration with initialization.
  • Confusing assignment with comparison.
  • Trying to reassign a const variable.
  • Declaring const without an initial value.
  • Redeclaring a let or const variable in the same scope.
  • Using invalid variable names.
  • Starting a variable name with a number.
  • Using spaces or hyphens in variable names.
  • Using reserved JavaScript keywords as variable names.
  • Forgetting that JavaScript variable names are case-sensitive.
  • Using meaningless names such as x, y, and z for important data.
  • Using var unnecessarily in modern JavaScript.
  • Thinking const makes arrays and objects completely immutable.
  • Creating accidental undeclared variables.
  • Using too many global variables.
  • Changing a variable to unrelated data types without a clear reason.
Common Mistakes
// ❌ Invalid name
let 1user = 'Rahul';

// ❌ Cannot reassign const
const score = 100;
score = 200;

// ❌ Cannot redeclare let
let city = 'Mumbai';
let city = 'Pune';

// ❌ Case mismatch
let userName = 'Rahul';
console.log(username);

Best Practices

  • Use const by default.
  • Use let only when the variable must be reassigned.
  • Avoid var in modern JavaScript unless its specific behavior is required.
  • Use meaningful and descriptive variable names.
  • Follow camelCase naming conventions.
  • Keep variable names consistent throughout the project.
  • Avoid unnecessary global variables.
  • Declare variables close to where they are used.
  • Do not reuse one variable for unrelated types of information.
  • Keep the purpose of each variable clear.
  • Use boolean names such as isActive, hasPermission, and canEdit.
  • Use plural names for collections such as users, products, and lessons.
  • Do not create variables that are never used.
  • Understand the difference between reassignment and mutation.
  • Keep variable scope as limited as reasonably possible.
Recommended Variable Style
const courseName = 'JavaScript';
const totalLessons = 27;

let currentLesson = 5;
let isCompleted = false;

currentLesson = 6;
isCompleted = true;

Frequently Asked Questions

What is a variable in JavaScript?

A variable is a named container used to store and access a value in a program.

Why do we need variables?

Variables allow programs to store, reuse, update, and calculate with data.

What is variable declaration?

Declaration means creating a variable and giving it a name.

What is initialization?

Initialization means assigning the first value to a variable.

What is reassignment?

Reassignment means replacing the current value of an existing changeable variable with a new value.

What is the difference between var, let, and const?

var is the older function-scoped declaration keyword, let is block-scoped and allows reassignment, and const is block-scoped and prevents reassignment of the variable binding.

Should I use var?

For most modern JavaScript code, use const by default and let when reassignment is required. var is mainly encountered in older code or specific situations.

Can a let variable change?

Yes. A variable declared with let can be reassigned.

Can a const variable change?

The const variable binding cannot be reassigned. However, the contents of an object or array stored through a const variable can still be modified.

Why must const be initialized immediately?

Because a const variable cannot later be reassigned, JavaScript requires an initial value when it is declared.

Can variable names contain numbers?

Yes, but a variable name cannot begin with a number.

Are variable names case-sensitive?

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

What naming style should I use?

JavaScript developers commonly use camelCase for variable names.

What does undefined mean?

undefined commonly indicates that a variable exists but does not currently contain an explicitly assigned value.

What is dynamic typing?

Dynamic typing means JavaScript variables are not permanently restricted to one data type.

What is variable scope?

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

What is variable shadowing?

Variable shadowing occurs when an inner scope declares a variable with the same name as one in an outer scope.

Why should I use const by default?

Using const clearly communicates that the variable binding is not expected to be reassigned, which can make code easier to understand.

Key Takeaways

  • Variables store values that programs need to use.
  • A variable has a name and a stored value.
  • Declaration creates a variable.
  • Initialization gives a variable its first value.
  • Assignment stores a value in a variable.
  • Reassignment replaces an existing value with a new value.
  • JavaScript provides var, let, and const.
  • var is the older variable declaration keyword.
  • let allows reassignment.
  • const prevents reassignment of the variable binding.
  • Use const by default in modern JavaScript.
  • Use let when reassignment is required.
  • Avoid var unless its specific behavior is needed.
  • Variable names must follow JavaScript naming rules.
  • Variable names are case-sensitive.
  • camelCase is the common naming convention.
  • Variables can store different types of values.
  • JavaScript is dynamically typed.
  • A declared variable without an assigned value can contain undefined.
  • Scope determines where a variable can be accessed.
  • let and const are block-scoped.
  • var is function-scoped.
  • Inner variables can shadow outer variables.
  • const arrays and objects can still have their contents modified.
  • Meaningful variable names make code easier to understand and maintain.

Summary

Variables are one of the most fundamental concepts in JavaScript. They allow programs to store information, reuse values, perform calculations, respond to changes, and create dynamic behavior.

JavaScript provides var, let, and const for variable declarations. Modern JavaScript generally uses const by default and let when a value must be reassigned. The older var keyword is still important to understand because it appears in existing JavaScript code.

A good JavaScript developer also understands the difference between declaration, initialization, assignment, and reassignment. Following valid naming rules and using meaningful camelCase names makes programs easier to read and maintain.

Variables can store many kinds of values, and JavaScript allows values of different types to be assigned dynamically. Variable accessibility is controlled by scope, while const prevents reassignment without automatically making arrays and objects immutable.

Lesson 5 Completed
  • You understand what JavaScript variables are.
  • You know why variables are required.
  • You understand declaration and initialization.
  • You understand assignment and reassignment.
  • You know how var, let, and const work.
  • You understand the differences between the three keywords.
  • You know JavaScript variable naming rules.
  • You understand camelCase naming conventions.
  • You know that JavaScript is dynamically typed.
  • You understand the basics of variable scope.
  • You understand variable shadowing.
  • You know how const behaves with arrays and objects.
  • You are ready to learn JavaScript Constants.
Next Lesson →

JavaScript Constants