Typeof in JavaScript: Checking Data Types Using the Typeof Operator

Typeof in JavaScript is an operator used for type checking and returns the data type of the operand passed to it. The operand can be any variable, function, or object whose type you want to find out using the typeof operator. Since JavaScript is a dynamically types language, meaning you do not have to specify the type of variables when declaring them, the typeof operator comes in handy to check the data type before execution. You can use the JavaScript typeof operator in the following two ways:

  • typeof operand
  • typeof (operand)

Different Types of Operands We Can Check Using Typeof in JavaScript

We can use typeof in JavaScript to check the data type of the following operands:

  • Number
  • String
  • Undefined
  • Boolean
  • Object
  • Symbol
  • Function

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Using Typeof in JavaScript With Different Operands

We will look at some examples where we use the JavaScript typeof operator to find out the data types of each operand mentioned above.

Typeof in JavaScript to Check Number Data Type

Here, we will pass numbers as operands and use the typeof operator and log the result to the console. We will use a positive integer, negative integer, zero, floating-point number, infinity, NaN, and Math equations as operands. We will also use the concept to explicitly typecasting and parsing a string to an integer or float and use it as an operand. The code below demonstrates the use of all of these operands.

console.log(typeof 12)

console.log(typeof -31)

console.log(typeof 0)

console.log(typeof 5.695)

console.log(typeof Infinity)

// Although NaN is Not-a-Number, it returns a number

console.log(typeof NaN)

console.log(typeof Math.LN2)

// Explicitly typecasting to number

console.log(typeof Number(`7`))

// Even if the value cannot be typecasted to integer, the result is a number

console.log(typeof Number(`Simplilearn`))

console.log(typeof parseInt(`86`))

console.log(typeof parseFloat(`40.05`))

Output:

Typeof_in_JavaScript_1.

As you can see, even though NaN is Not-a-Number, the typeof operator returns number when checking NaN type. Also, explicitly typecasting returns a number even if we typecast a string to an integer.

Typeof in JavaScript to Check String Data Type

For this example, we will pass string operands. The typeof in JavaScript will return “string” as the result of an empty string, a string of characters, a string of multiple words, numbers in quotes, use of typeof, and conversions with the String function. Here’s an example.

console.log(typeof '');

console.log(typeof 'Simplilearn');

console.log(typeof 'Welcome to JavaScript Tutorials');

console.log(typeof '10');

// typeof will always return a string as a result

console.log(typeof (typeof 15));

// Using String function, which is safer than toString conversion

console.log(typeof String(20));

Output:

Typeof_in_JavaScript_2.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Typeof in JavaScript to Check Undefined Data Type

This example will show the use of typeof in JavaScript to check undefined operand types. We will use the undefined keyword, a declared but undefined variable, and an undefined variable as operands and log the result to the console. One thing to note here is that we are using Null and not null as the former returns undefined while the latter returns object as the type of the operands.

// undefined keyword

console.log(typeof undefined)

// Declared but undefined variable

let a

console.log(typeof a);

// Undefined variable

console.log(typeof v);

Output:

Typeof_in_JavaScript_3

Typeof in JavaScript to Check Boolean Data Type

For this example, we will pass boolean values as operands. The typeof in JavaScript will return boolean for true, false, values explicitly typecast as boolean using the Boolean() function, and when two “!” (Logical NOT) operators are used.

console.log(typeof true);

console.log(typeof false);

console.log(typeof Boolean(1));

console.log(typeof !!(1));

Output:

Typeof_in_JavaScript_4

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Typeof in JavaScript to Check Object Data Type

The below example passes objects as operands with typeof in JavaScript. The following operands will return the object as a result.

console.log(typeof null);

console.log(typeof [1, 2, 'hello']);

console.log(typeof {a: 'hello', b: 'welcome'});

console.log(typeof [1, 2, 3, 4]);

Output:

Typeof_in_JavaScript_5

Although null holds nothing, it returns an object, as you can see in the output. Besides, an array, a set, and an object literal of key: value pair also returns “object” as a result. Additionally, using Date(), Number(), String(), and Boolean() as a constructor also returns “object.” The example below demonstrates the same.

console.log(typeof new Date());

console.log(typeof new Boolean(true));

console.log(typeof new Number(1));

console.log(typeof new String('abc'));

Output:

Typeof_in_JavaScript_5

Note: Although Number(), String(), and Boolean() can be used as constructors, it is a frowned-upon practice and should be avoided.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Typeof in JavaScript to Check Symbol Data Type

In this example, we will use the symbol data type operands. The JavaScript typeof operator will return “symbol” when we pass an empty Symbol() function, a single parameter Symbol() function, and Symbol.iterator. Here’s an example for the same.

console.log(typeof Symbol());

console.log(typeof Symbol('parameter'));

console.log(typeof Symbol.iterator);

Output:

Typeof_in_JavaScript_6.

Typeof in JavaScript to Check Function Data Type

We will get “function” as the output in this example when we pass the operands to typeof in JavaScript. The typeof operator will return this result when we give a user-defined function, a predefined function, or a class as an operand.

console.log(typeof function() {});

console.log(typeof Math.tan);

console.log(typeof class C {});

Output:

Typeof_in_JavaScript_7

Common Use Cases of Typeof in JavaScript

Some of the most common uses of typeof in JavaScript are:

  • Type-checking while accepting parameters in a function. Refer to the below example for a better understanding. The example declares and defines a function to multiply two integers. The typeof operator is used to check if the parameters passed to the function are integers or not. The first code gives integer values and gets the required product. On the other hand, the second code will pass an integer and a string and get the error message.

function product(x, y) {

  // Type-checking

  if (typeof x !== 'number' || typeof y !== 'number') {

    throw 'Arguments must be a number'

  };

  return x * y;

}

console.log(product(4, 5))

Output:

Typeof_in_JavaScript_8

As you can see, we passed 4 and 5 in this code and got the product 20. Now let’s combine an integer and a string and see the result logged to the console.

function product(x, y) {

  // Type-checking

  if (typeof x !== 'number' || typeof y !== 'number') {

    throw 'Arguments must be a number'

  };

  return x * y;

}

console.log(product(4, 'hello'))

Output:

Typeof_in_JavaScript_9.

  • Another use of the JavaScript typeof operator is to check if a variable is defined, or in other words, check existence. Here, we will create a function to add two numbers and check if both the variables are defined or not.

let x = 20;

let y;

function sum(x, y) {

  // Checking existence

  if (typeof x === 'undefined') {

    throw 'x is undefined'

  };

  if (typeof y === 'undefined') {

    throw 'y is undefined'

  }

  return x + y;

}

console.log(sum(x, y))

Output:

Typeof_in_JavaScript_10.

Conclusion

In this article, you have learned about typeof in JavaScript and how you can use the typeof operator to check the data type of operands. If you want to know more about such JavaScript fundamentals, you can enroll in Simplilearn’s JavaScript Certification Course. The course is tailored to help the students learn JavaScript from scratch and master the essential fundamentals through curated videos and other learning tutorials. Pursuing this course will help you develop and hone the programming skills and prepare you for a rewarding job position in multinational companies.

Besides the course, you can also sign up on our SkillUp platform, a Simplilearn initiative. The platform offers numerous free online courses to help with the basics of multiple programming languages, including JavaScript. Additionally, you can also opt for our Post Graduate Program in Full Stack Web Development. Mastering a single language is not enough in today’s competitive world as employers are looking for intellectuals with multi-language skills, and our course is made just for that. It helps you grasp the fundamentals of the most popular development languages and the essential tools relevant to them. It also offers certification upon completing the course to add credibility to your skills. To put it simply, the course is well adept at helping you pursue a strong career in the software and web development field.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.