JavaScript typeof

Summary: in this tutorial, you’ll learn how to use the JavaScript typeof operator that returns a string representing the type of a value.

Introduction to the JavaScript typeof operator #

The typeof operator accepts an operand and returns a string representing the type of the operand. The following shows the syntax of the typeof operator:

typeof(operand)

In this syntax, the operand can be a value, a variable, or an expression. Alternatively, you can use the typeof operator without the parentheses like this:

typeof operand

Note that if the operand is an expression, you need to use the parentheses to make the syntax valid.

JavaScript typeof examples #

The following example shows how to use the typeof operator with values of various types:

let type;

type = typeof 'Hi';
console.log(type); // 'string'

type = typeof 100;
console.log(type); // 'number'

type = typeof 100n;
console.log(type); // 'bigint'

type = typeof false;
console.log(type); // 'boolean'

type = typeof Symbol('morning');
console.log(type); // 'symbol'


type = typeof undefined;
console.log(type); // 'undefined'


type = typeof new Date();
console.log(type); // 'object'

In JavaScript, null is a primitive value of the null type. However, its type is not null but object because JavaScript treats null as an empty object:

type = typeof null;
console.log(type); // 'object'

Technically, JavaScript treats functions as objects. Therefore, their types are 'object'. However, functions have some special properties, JavaScript needs to differentiate functions and other objects via using a typeof operator. For example:

function add(x, y) {
  return x + y;
}

let type = typeof add;
console.log(type); // 'function';

JavaScrippt typeof operator & parentheses #

When passing an expression to the typeof operator, you need to use parentheses. For example:

let type = typeof (100 + '10');
console.log(type);

Output:

'string'

In this example, the expression 100 + '10' returns the string '10010'. Therefore, its type is 'string'. If you don’t use the parentheses, you’ll get an unexpected result. For example:

let type = typeof 100 + '10';
console.log(type);

Output:

'number10'

In this example, the typeof 100 returns 'number'. Therefore, the result is a string that is the concatenation of the string 'number' and '10'.

Summary #

  • Use JavaScript typeof operator to get a string that represent the value type.

Was this helpful?