JavaScript typeof: How to Check Datatype in JavaScript

JavaScript typeof is a built-in operator that returns a data type of its operand as a string. The operand can be any object, function, or variable.

Syntax

typeof operand

// OR

typeof (operand)

Example 1: typeof String

The operand parameter represents the object or primitive whose type will be returned.

console.log(typeof 'appdividend');

Output

Javascript Typeof Example | typeof Operator Tutorial

Example 2: typeof Number

We can also check the Number as well.

let appInt = 21;

console.log(typeof (appInt));

It will return the Number.

Next, let’s check the object.

const obj = {
 name: 'krunal',
 age: 26
};

console.log(typeof (obj));

Output

typeof object in javascript

Example 3: typeof and === operator.

We can compare the variable’s datatype using the typeof operator and get the result as true or false.

console.log(typeof 'appdividend' === 'string');

Output

Use typeof as boolean

We can do the same for the Number and other data types.

console.log(typeof 21 === 'number');

We get true; if the data type does not match, it will return false.

Example 4: typeof undefined

In JavaScript, the variable without any value has the value undefined. Therefore, the type is also undefined.

let jet;

console.log(typeof (jet));

Output

typeof Undefined

Example 5: typeof null

The null is an exception to JavaScript since the beginning.

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

The output is true. That means JavaScript counts null as an object.

Since starting, JavaScript values were represented as the type tag and a value. The type tag for objects was 0. The null was described as the NULL pointer (0x00 in most platforms).

Consequently, the null had 0 as the type tag, hence the “object” typeof return value.

Example 6: typeof NaN

The type of NaN, which stands for Not a Number, is, surprisingly, a number. This is because, in computing, NaN is technically a numeric data type.

console.log(typeof NaN);

Output

number

However, it is the numeric data type whose value cannot be represented using the actual numbers.

This also explains why not all NaN values are equal.

const x = NaN;
const y = NaN;

console.log(x === y);

Output

false

Example 7: typeof array

The typeof an array is an object. In JavaScript, arrays are technical objects with certain behaviors and abilities.

let st3 = ['Eleven', 'Dustin', 'Lucas'];

console.log(typeof st3);

Output

object 

We can differentiate an Array object from an Object object using the Array.isArray() method.

Example 8: typeof class

console.log(typeof class Foo { });

Output

function

Conclusion

To check a data type of a variable in JavaScript, you can use the typeof operator. For example, typeof 21 returns “Number” and typeof khushi returns “String”.

1 thought on “JavaScript typeof: How to Check Datatype in JavaScript”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.