Variables are one of the most important concepts in JavaScript. They are used to store data that  can be used and can also be  changed while it runs.

Think of a variable as a labeled box where you can keep some information and use it later.


What is a Variable?

A variable can be defined as a named container in which the programmer can store data values and can also change the data value later in the program. It can be used to store values like:

  • person's age

  •  total score

  •  login status (true/false)

Instead of writing the same value again and again, we store it in a variable and use the variable name.


Example (Real-life analogy)

Box label: age
Box value: 21

In JavaScript:

 

The value stored in a variable can be changed. You can re-assign different values to the same variable in different parts of the code.
Example


Why Do We Need Variables?

Variables help us to:

  • Store different data values

  • Reuse values

  • Write dynamic and flexible programs

  • Make code easier to read and maintain


JavaScript provides three keywords to declare variables:
  • var

  • let

  • const

Each of them behaves differently.


Rules for naming a Variable:

There are a set of rules which we need to follow while naming a variable-

1 Variable names can include combinations of Letters(a-z, A-Z), Digits(0-9), Underscore and Dollar Sign($).

2 A variable name can not start with a number. Name like '8val', '12a' are invalid,

3 Spaces or Special symbols cannot be included in a variable name. Names like first name, first-name, first@name are all invalid.

4 Variable names are case sensitive. 'name' and 'Name' would be treated as different variable

Example

5 JavaScript has some reserved words (let, function, return, etc.) which cannot be used while naming variables.