typeof operator

The typeof operator allows you to determine a parameter type (a number, string, object). The operator returns a string containing the type ('number', 'string', 'object').

For null, the operator returns 'object' (this is a recognized language bug). For functions, the operator returns 'function'. This is done for convenience, as there is no the 'function' type.

Syntax

The typeof operator has a 2 syntaxes (both syntaxes work the same way):

javascripttypeof parameter;
typeof(parameter);

Example

Let's see how typeof works with a number:

javascripttypeof 1;

As a result of the executed code, we will get the value number:

javascript'number'

Example

Now let's set the parameter to a string:

javascripttypeof 'str';

The code execution result:

javascript'string'

Example

Now we specify the boolean true value in the parameter:

javascripttypeof true;

The code execution result:

javascript'boolean'

Example

Let's see what type the undefined value has:

javascripttypeof undefined;

After executing the code, we will also get undefined:

javascript'undefined'

Example

Now let's find out the type of an empty object:

javascripttypeof {};

The code execution result:

javascript'object'

Example

Now let's find out the type of an empty array:

javascripttypeof [];

As a result, we also get 'object':

javascript'object'

Example

Let's find out the type of null value:

javascripttypeof null;

As a result, we also get 'object', which is a recognized language bug:

javascript'object'

Example

Now let's define the type of an empty function:

javascripttypeof function() {};

After executing the code, we get 'function', even though there is no such type. This string is needed for the convenience of a user when defining a function:

javascript'function'

Example

Let's write a function that will display only numbers:

javascriptfunction printNumber(number) {
  if (typeof number === 'number') {
    console.log(number);
  }
}

printNumber(2);
printNumber('str');
printNumber(3);

See also

  • the isNaN function
    that checks for NaN
  • the isFinite function
    that checks a number for finiteness