JavaScript Data Types

JavaScript is a loosely or weakly typed language. Therefore, whatever the value assigned to a variable, the variable changed its typed based on the assigned value.

Or we can say, in JavaScript, there is no need to declare or define the type of variable before its use.

In JavaScript, here are the list of 5 data types based on values:

  1. string - Used to store string type value like "fresherearth"
  2. number - Used to store number type value like 120
  3. boolean - Used to store boolean type value. The two boolean type values are true and false
  4. object - Used to store object type value like [1, 2, 3, 4, 5]
  5. function - Used to store function type value like function () {}

For example:

x = "fresherearth";    // x is of string type
x = 120;               // now x is of number type
x = true;              // now x is of boolean type

See the above example, there is no need to declare the type of variable before initializing any value of that type.

The JavaScript typeof operator is used to find the type of value/variable. For example:

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

   <p id="para1"></p>
   <p id="para2"></p>
   <p id="para3"></p>
   <p id="para4"></p>
   <p id="para5"></p>
   
   <script>
      document.getElementById("para1").innerHTML = typeof "fresherearth";
      document.getElementById("para2").innerHTML = typeof 10;
      document.getElementById("para3").innerHTML = typeof true;
      document.getElementById("para4").innerHTML = typeof [1, 2, 3, 4, 5];
      document.getElementById("para5").innerHTML = typeof function () {};
   </script>
   
</body>
</html>
Output

JavaScript allows three keyword that are: var, let, and const to declare a variable.

JavaScript Online Test


« Previous Tutorial Next Tutorial »