Intro

The typeof operator is a JavaScript operator that returns the data type of its operand in a form of a String. An operand can be a variable, a function or an object.

It is surely one of the most underrated features of JavaScript. Some new developers don't even know it exists until they encounter it.

In this article, we will unleash the potential of the typeof operator for validating data.

Example

console.log(typeof 'Random Code Tips'); // string
console.log(typeof 42); // number
console.log(typeof true); // boolean
console.log(typeof function() {}); // function
console.log(typeof {website: 'Random Code Tips'}); // object

Usage

So how do we use it in validation?

Let's say we have an  add function that accepts  2 arguments as addends.

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

This function is pretty basic, it just adds the addends and return the result. It will work if you pass a number to x and y, say add(1,1) it will return 2.

But what if the user passed a non-number argument? Yes, it will throw an unhandled error. So what we gotta do is to add some validation to our add function to make sure that it handles the arguments properly so that the code won't break.

We will do that by using the typeof operator.

function add(x, y) {

  // validation
  if(typeof x !== 'number' || typeof y !== 'number') {
    return 'Error: Addends must be a number';
  }
  
  return x + y;
}

Notice the condition in the if statement above.

This basically means that if the typeof x is not a  'number' OR the typeof y is not a  'number', then one of the addends is invalid; therefore throw an error.

Live

Now let's see it in action.

Thanks for reading!