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>
   
   <script>
      var x = "codescracker.com";
      document.write("1. ", x, "<BR>");
      function myFun() {
         document.write("2. ", x, "<BR>");
         x = "codes cracker";
         document.write("3. ", x, "<BR>");
      }
      myFun();
      document.write("4. ", x, "<BR>");
      var x = "JavaScript is Fun!";
      document.write(x);
   </script>
   
</body>
</html>
Output

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>
   
   <script>
      var a;
      document.write(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 »