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.
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.
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.
- Using var keyword
- Using let keyword
- Using const keyword
Creating a variable is a two step process :
- Declaring a variable
- 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:
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:
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.