offline version v3


22 of 264 menu

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):

typeof parameter; typeof(parameter);

Example

Let's see how typeof works with a number:

typeof 1;

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

'number'

Example

Now let's set the parameter to a string:

typeof 'str';

The code execution result:

'string'

Example

Now we specify the boolean true value in the parameter:

typeof true;

The code execution result:

'boolean'

Example

Let's see what type the undefined value has:

typeof undefined;

After executing the code, we will also get undefined:

'undefined'

Example

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

typeof {};

The code execution result:

'object'

Example

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

typeof [];

As a result, we also get 'object':

'object'

Example

Let's find out the type of null value:

typeof null;

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

'object'

Example

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

typeof 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:

'function'

Example

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

function 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
enru