JavaScript Data Types

JavaScript's versatility in handling various data formats is a key feature that contributes to its power. JavaScript allows programmers to create sophisticated applications and interactive websites because it supports a wide variety of data types, from strings and numbers to arrays and objects.

Because JavaScript is a dynamically typed language, we don't need to declare the type of a variable before using it, which is one of its great features. As a result, whatever value was assigned to a variable, the variable's type changed as a result of the assigned value.

Variables in JavaScript can be given values of various data types at various points while a program is being executed. A variable might be given a string value at one point and a numeric value at another. Because of its adaptability, JavaScript is a strong and useful language, but it can also cause unexpected behavior if not used carefully.

Primitive data types in JavaScript are the most fundamental data types and include:

JavaScript supports reference data types in addition to primitive data types, such as:

For example:

x = "codescracker";    // 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 a variable before initializing any value of that type.

JavaScript typeof: find the data type of a variable or value

The JavaScript typeof operator is used to find the type of value or 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 "codescracker";
      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 keywords to declare a variable: varlet, and const.

Consider the following code as another example demonstrating the "typeof" operator in JavaScript:

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

   <p id="para1"></p>
   <p id="para2"></p>
   
   <script>
      let x = 10;
      document.getElementById("para1").innerHTML = typeof x;
      document.getElementById("para2").innerHTML = typeof "codescracker";
   </script>
   
</body>
</html>
Output

The syntax of the typeof operator in JavaScript is:

typeof x

x refers to the variable or value whose type we need to find.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!