The JavaScript typeof operator returns the data type of a specified operand .
Syntax of the typeof
Operator
The typeof
operator accepts one operand. Here’s the syntax:
The operand
represents a primitive or non-primitive value.
Example
typeof " CodeSweetly " ; // Returns "string"
typeof ` CodeSweetly ${ new Date () . getFullYear () } ` ; // Returns "string"
typeof 123 ; // Returns "number"
typeof Infinity ; // Returns "number"
typeof NaN ; // Returns "number"
typeof new Date () . getFullYear (); // Returns "number"
typeof { name: " Oluwatobi " , company: " CodeSweetly " }; // Returns "object"
typeof [ " Oluwatobi " , " CodeSweetly " ]; // Returns "object"
typeof null ; // Returns "object"
typeof new Date (); // Returns "object"
// Undefined typeof data:
typeof undefined ; // Returns "undefined"
typeof undeclaredVariable ; // Returns "undefined"
let variableDeclaredWithNoAssignedValue ;
typeof variableDeclaredWithNoAssignedValue ; // Returns "undefined"
typeof function getMyType () {}; // Returns "function"
typeof Math . random ; // Returns "function"
typeof " Oluwatobi " . constructor ; // Returns "function"
typeof true ; // Returns "boolean"
typeof false ; // Returns "boolean"
typeof 123 n ; // Returns "bigint"
typeof 9 n ; // Returns "bigint"
Try Editing It
The snippet above used the typeof
operator to return the data types of the specified values.
Important Stuff to Know about the typeof
Operator
typeof null === object
is a bug from JavaScript’s first version.
The typeof
operator has higher precedence than ternary or binary operators. Therefore, you need parentheses to evaluate non-unary operands correctly. For instance, consider the following snippet:
typeof true + " Love " ; // Returns "booleanLove"
typeof ( true + " Love " ); // Returns "string"
typeof 7 > 5 ? " Correct! " : false ; // Returns false
typeof 7 < 5 ? " Correct! " : false ; // Returns false
typeof ( 7 > 5 ? " Correct! " : false ); // Returns "string"
typeof ( 7 < 5 ? " Correct! " : false ); // Returns "boolean"
Try Editing It
The snippet above returned the correct results only where we used parentheses to evaluate the binary and ternary operators.