JavaScript typeof Operator

In this tutorial, you will learn about JavaScript typeof operator with the help of examples.

The typeof operator returns the type of variables and values. For example,

const a = 9;

console.log(typeof a); // number
console.log(typeof '9'); // string
console.log(typeof false); // boolean

Syntax of typeof Operator

The syntax of typeof operator is:

typeof operand

Here, operand is a variable name or a value.


typeof Types

The possible types that are available in JavaScript that typeof operator returns are:

Types typeof Result
String "string"
Number "number"
BigInt "bigint"
Boolean "boolean"
Object "object"
Symbol "symbol"
undefined "undefined"
null "object"
function "function"

Example 1: typeof for String

const str1 = 'Peter';
console.log(typeof str1); // string

const str2 = '3';
console.log(typeof str2); // string

const str3 = 'true';
console.log(typeof str3); // string

Example 2: typeof for Number

const number1 = 3;
console.log(typeof number1); // number

const number2 = 3.433;
console.log(typeof number2); // number

const number3 = 3e5
console.log(typeof number3); // number

const number4 = 3/0;
console.log(typeof number4); // number

Example 3: typeof for BigInt

const bigInt1 = 900719925124740998n;
console.log(typeof bigInt1); // bigint

const bigInt2 = 1n;
console.log(typeof bigInt2); // bigint

Example 4: typeof for Boolean

const boolean1 = true;
console.log(typeof boolean1); // boolean

const boolean2 = false;
console.log(typeof boolean2); // boolean

Example 5: typeof for Undefined

let variableName1;
console.log(typeof variableName1); // undefined

let variableName2 = undefined;
console.log(typeof variableName2); // undefined

Example 6: typeof for null

const name = null;
console.log(typeof name); // object

console.log(typeof null); // object

Example 7: typeof for Symbol

const symbol1 = Symbol();
console.log(typeof symbol1); // symbol

const symbol2 = Symbol('hello');
console.log(typeof symbol2); // symbol

Example 8: typeof for Object

let obj1 = {};
console.log(typeof obj1); // object

let obj2 = new String();
console.log(typeof obj2); // object

let obj3 = [1, 3, 5, 8];
console.log(typeof obj3); // object

Example 9: typeof for Function

let func = function () {};
console.log(typeof func); // function

// constructor function
console.log(typeof String); // function

console.log(typeof Number); // function

console.log(typeof Boolean); // function

Uses of typeof Operator

  • The typeof operator can be used to check the type of a variable at a particular point. For example,
let count = 4;
console.log(typeof count);

count = true;
console.log(typeof count);
  • You can perform different actions for different types of data. For example,
let count = 4;
if(typeof count === 'number') {
    // perform some action
}
else if (typeof count = 'boolean') {
      // perform another action
}