JavaScript var Keyword | Declare a Global Variable

The JavaScript var keyword is used to declare a global variable, that can be updated as well as re-declared. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>1. <span id="span1"></span></p>
   <p>2. <span id="span2"></span></p>
   <p>3. <span id="span3"></span></p>
   <p>4. <span id="span4"></span></p>
   <p id="para1"></p>
   
   <script>
      var x = "fresherearth.com";
      document.getElementById("span1").innerHTML = x;
      function myFun() {
         document.getElementById("span2").innerHTML = x;
         x = "codes cracker";
         document.getElementById("span3").innerHTML = x;
      }
      myFun();
      document.getElementById("span4").innerHTML = x;
      var x = "JavaScript is Fun!";
      document.getElementById("para1").innerHTML = x;
   </script>
   
</body>
</html>
Output

1.

2.

3.

4.

Note - The default value of variable, declared using the var keyword, is undefined. Therefore, accessing a var variable without its initialization, returns or prints undefined. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      var a;
      document.getElementById("xyz").innerHTML = a;
   </script>
   
</body>
</html>
Output

JavaScript var Syntax

The syntax of var keyword in JavaScript, is:

var variableName = variableValue;

The variableValue is optional. That is, we can assign the value either at the time of declaration, or later. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p>The sum of 10 and 20 is <span id="x"></span></p>
   <script>
      var a = 10;
      var b = 20;
      var sum;
      sum = a + b;
      document.getElementById("x").innerHTML = sum;
   </script>
   
</body>
</html>
Output

The sum of 10 and 20 is

As you can see from the above example, the variable a and b are initialized at the time of its declaration. Whereas the variable sum is initialized later, after the declaration.

JavaScript Online Test


« Previous Tutorial Next Tutorial »