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

  • Variable name must starts with a letter (A-Z or a-z), a dollar sign ($), or an underscore (_)
  • Use letters, digits (0-9), underscores, and dollar signs to name a variable
  • Do not use any keyword to name a variable
  • Variable names in JavaScript are case-sensitive. Therefore, num, Num, NUM are all different variables

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

  • num
  • x
  • _x
  • $x
  • first_name
  • area34
  • ar3t
  • tr_$s_3_

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋