JavaScript Variables

Variables in JavaScript are the containers for the data used in the program/application. For example:

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

   <p>Sum of <span id="one">10</span> and <span id="two">20</span>
   is <span id="res"></span></p>
   
   <script>
      var numOne = parseInt(document.getElementById("one").innerHTML);
      var numTwo = parseInt(document.getElementById("two").innerHTML);
      var result = numOne + numTwo;
      document.getElementById("res").innerHTML = result;
   </script>
   
</body>

</html>
Output

Sum of 10 and 20 is

In above example, after initializing the value to variable say numOne, writing numOne anywhere in the program, means writing the value inside it or represents the value stored in it.

Types of Variables in JavaScript

In JavaScript, a variable can be declared using any of the following three keywords:

  1. var
  2. let
  3. const

Depending on the use of keyword to declare a variable in JavaScript, there are three types of variables, that are:

  1. var Variable
  2. let Variable
  3. const Variable

Note - Use var to declare a global variable, that can be updated and re-declared.

Note - Use let to declare a block-scoped variable that can be updated, but can not be re-declared.

Note - Use const to declare a block-level variable that can neither be updated nor be re-declared. A const variable must be initialized with a value at the time of its declaration.

Rules to Name a Variable in JavaScript

Here are the list of some valid variable names example in JavaScript:

JavaScript Online Test


« Previous Tutorial Next Tutorial »