Back to all posts

Typeof Operator in JavaScript


You can use the typeof operator to find the data type of a JavaScript variable.

The Basics of typeof

The typeof operator in JavaScirpt return a string indicating the data type of the operand. It helps you perform type-checking operations or handle values dynamically based on their types. The suntax of the typeof operator is as follows:

typeof operand

Please observe:

  • The data type of NaN is number
  • The data type of an array is object
  • The data type of a date is object
  • The data type of null is object
  • The data type of an undefined variable is undefined *
  • The data type of a variable that has not been assigned a value is also undefined *

Examples

typeof "John"                 // Returns "string"
typeof 3.14                   // Returns "number"
typeof NaN                    // Returns "number"
typeof false                  // Returns "boolean"
typeof [1,2,3,4]              // Returns "object"
typeof {name:'John', age:34}  // Returns "object"
typeof new Date()             // Returns "object"
typeof function () {}         // Returns "function"
typeof myCar                  // Returns "undefined" *
typeof null                   // Returns "object"

let isTrue = true;
console.log(typeof isTrue);  // Output: "boolean"

Additional Considerations Although the typeof operator provides valuable insights into the data type of a value, there are a few important points to keep in mind:

  • The typeof null expression returns "object" instead of "null". This is a historical quirk in JavaScript and not a true representation of the null value’s type.
  • The typeof operator does not differentiate between an array and a regular object. Both return "object".
  • The typeof operator does not provide information about the specific built-in object types like Date, RegExp, or Error. They all fall under the general "object" category.