Variables In Javascript

The basic meaning of a variable is something that is not consistent or liable to change. Similarly, in programming, a variable is a data container whose value/data is subjected to change. In the figure below, you can see how variables are stored in the memory. X and Y are the two containers or variables that have data in them, you can change the data anytime you want.

Figure 1

The value stored in the variable can be an integer or a string or a boolean value. In Figure 1 both X and Y variables have integer value stored in them.

Figure 2

In Figure 2, the variable name is “firstName” and it possesses a string value, John. The second variable name is “isValid” and it possesses a boolean value.

In Javascript there are three ways of creating Variables:

  1. Using var keyword
  2. Using let keyword
  3. Using const keyword

Creating a variable is a two step process :

  1. Declaring a variable
  2. Initializing a variable

Declaring a variable means you just give a name to the variable and memory is allocated to that variable.

var x ; // This statement declares a variable and allocates memory to the variable.

Initializing a variable means assigning a value to the declared variable.

x=5; // This statement initializes/defines a variable.

We can declare and define a variable in a single line also, like :

var x = 5;

As you saw above we used var to declare a variable, instead of var we could use the let or const keyword. For example :

let x = 7;

const y = 8;

Once variable is initialized, its value can be used anywhere. For Example:

Figure 3


Figure 4

Wherever we want value John we can just use variable name firstName. We can even change the value of firstName to something else if we want. For example:

Figure 5
Figure 6

In Figure 5 you see that on the first line we have declared and defined variable firstName and its value is John. In second line we are just redefining variable firstName i.e. we are just changing the value of the variable which is already declared. Now, the output will be “My first name is Rachel” , as the value of the variable firstName is updated and browser will take the updated value.

This post was about what are variables and how to create them in JavaScript .

In the next post, you will get to know about the very important concept of Hoisting in JavaScript and the difference between declarations using var, let, and const.