2. JavaScript Variables
2.1. Using var keyword
var keyword is used to create and declare a variable. To construct a JavaScript statement, you
can refer to our example below. It is possible to reassign or redefine the values of the
variables.
var x; // without initializing
var x = 5; // initialize with a number
- <!DOCTYPE html>
- <html>
- <body>
- <h2>Variables of JavaScript</h2>
- <p>x is described as a variable in this example. Then, the value of x is assigned to 5: </p>
- <script>
- var x=5;
- document.write(x);
- </script>
- </body>
- </html>
The following outcome will result in this:
Determining what we have learned so far, the statement declaring a variable (x), using a
single equal sign, assigns a number data type (5) then followed by a semicolon (;).
A variable can change as it was used the first time and was declared with var.
var x = 5; // x was worth 5
x = 6; // now it’s worth 6
The variable holds one value at a time, and because the program runs from top to bottom, x
has now a value of 6.
Refer to this example of a variable that has a different type of data:
- <html>
- <body>
- <h2>JavaScript Variables</h2>
- <script>
- var greeting = "Oh hi Pisay";
- document.write(greeting);
- </script>
- </body>
- </html>
The greeting variable now includes the string Oh hi Pisay!
Multiple variables can be declared in a single line, separating them with commas.
var x = 5, var greeting = "Oh hi Pisay",…;
or variables could also be defined like below:
var x=y=z=5;
wherein x, y and z will all have 5 as their initial value.
Refer to the given example:
- <html>
- <body>
- <script>
- var x = 5;
- document.write("The value of variable is: " + x);
- document.write("</br>After redeclaration,</br>");
- var greeting = "Oh hi Pisay";
- document.write("The value of variable is: " + greeting);
- </script>
- </body>
- </html>
Before program execution, all the declarations in JavaScript (including variable declarations)
are processed. In this way, declaring a variable anywhere is equivalent to declaring it at the top of the
code. This provides JavaScript with the functionality to use the variables before their declarations
within the code. We call this behavior of variables “var hoisting”.
It is always recommended in programming to declare the variables before using them. This is
to avoid unintentional redeclaration of a variable.
This type of variable declaration method is never used by programmers. Other two methods
you need to consider are either let or const for your variables.