JavaScript Variables: Complete Guide for Beginners with Examples

The Variables are one of the most fundamental concepts in JavaScript. They act as containers that store data values allowing developers to save, update & manipulate information throughout a program.

Whether you're building a simple calculator or a complex web application understanding variables is essential for writing efficient & maintainable JavaScript code.

What Are Variables in JavaScript?

A variable is a named storage location used to hold data in memory.

Example :

let name = "kumar";

console.log(name);

Output:

kumar

In this example:

  • name is the variable name.
  • "kumar" is the value stored inside the variable.

Why Do We Need Variables?

The Variables help us:

  • Store user input
  • Save application data
  • Perform calculations
  • Reuse values
  • Make code dynamic and flexible

Example

let price = 100;

let quantity = 3;

let total = price * quantity;

console.log(total);

Output:

300

Declaring Variables in JavaScript

The JavaScript provides three ways to declare variables:

  1. var
  2. let
  3. const

Using var

Before ES6, var was the primary way to declare variables.

Syntax :

var age = 25;

Example :

var city = "New York";

console.log(city);

Output:

New York

Using let

Introduced in ES6, let is the preferred way to declare variables that may change later.

Syntax :

let age = 25;

Example :

let count = 10;

count = 20;

console.log(count);

Output:

20

Using const

The const keyword is used for values that should not change.

Syntax :

const PI = 3.14159;

Example :

const country = "A";

console.log(country);

Output:

A

Variable Naming Rules

The JavaScript variable names must follow certain rules.

Allowed

let username;

let firstName;

let _value;

let $price;

Not Allowed

let 123name;

let user-name;

let let;

Rules

  • Must start with a letter, _ or $
  • Cannot start with a number
  • Cannot contain spaces
  • Cannot use reserved keywords

Variable Initialization

Assigning a value to a variable is called initialization.

Example :

let language = "JavaScript";

You can also declare first and assign later.

let language;

language = "JavaScript";

Multiple Variable Declarations

You can declare multiple variables in one statement.

Example :

let a = 10,

    b = 20,

    c = 30;

console.log(a, b, c);

Real-World Example

const productName = "Laptop";

const price = 50000;

let quantity = 2;

let totalCost = price * quantity;

console.log("Product:", productName);

console.log("Total Cost:", totalCost);

Output :

Product: Laptop

Total Cost: 100000

Conclusion

The JavaScript variables are the foundation of every program. They allow developers to store, update & manage data efficiently. The Modern JavaScript development primarily relies on let & const offering better scope control & code compared to var.