Identifying Data Types with JavaScript's typeof Operator

JavaScript's typeof operator is a really powerful and commonly used tool that is sometimes misunderstood by beginners.

The typeof does one thing: it helps us identify the data type of a given value.

It's important to know that typeof is an operator instead of a function.

However, instead of acting like the plus sign operator, which expects two operands on the left and the right, typeof is what's known as a unary operator, meaning it expects and it operates on a single operand, which we put after the word typeof.

To use it, typeof in all lowercase then write the thing you want to check.

Trying typeof on an int or float, you'll see number. A string like hello will show you string:


typeof 35 // "number"
typeof 3.4 // "number"
typeof "hello" // "string"

However, If you try typeof on an array, it doesn't tell us array because In JavaScript, arrays are considered objects. The same is true when using typeof with actual objects.


typeof [1, 2, 3]; // "object"
typeof {}; // "object"

There are some quirks with the typeof operator in JavaScript.

If you run typeof on the value null, it returns "object" due to a historical bug in JavaScript. This is a gotcha, as it doesn't return "null" as you might expect:


typeof null; // "object"

However, if you use typeof on the undefined value, it returns "undefined":


typeof undefined; // "undefined"

Using typeof on NaN (Not a Number) returns "number":


typeof NaN; // "number"

The typeof operator works with Booleans as well:


typeof false; // "boolean"

Why Use Typeof?

The main reason to use the typeof operator is for basic type checking and validation.

JavaScript is a dynamically typed language, meaning a variable can hold any sort of value and change data types:


let x = 23;
x = "aslkjd";
x = true;

However, this dynamic typing can lead to bugs when a variable unexpectedly holds a different type of value (this is the whole reason TypeScript exists!)

Basic Type Checking with typeof Operator

In JavaScript, you can use the typeof operator to perform some basic type checking and validation.

Let's consider a simple example of a function called add that expects two arguments, but doesn't specify that they should be numbers. This means you could pass in strings, Booleans, or objects:


function add(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
} else {
throw new Error('Both arguments must be numbers');
}
}

In the add function, we use typeof to make sure that both a and b are numbers. If they are, we return their sum using the + operator. Otherwise, we throw an error.


add(2, 3); // Works fine
add(2, 'd'); // Throws an error: Both arguments must be numbers

Without the type checking, if you try to add a number and a string, JavaScript will concatenate them into a string, which is probably not the behavior you want from an add function:


function addWithoutTypeChecking(a, b) {
return a + b;
}
addWithoutTypeChecking(2, 'd'); // Returns '2d'

By adding type checking using typeof, you can ensure that both a and b are numbers, making the function's behavior more predictable and less prone to errors.

Comparing Values with typeof

When making comparisons with the result of typeof, it always returns a lowercase string as the result.

For example, when comparing typeof true to the string "Boolean", make sure to use a lowercase "b":


typeof true === "Boolean" // This is false
typeof true === "boolean" // This is true

Using typeof with Conditional Statements

Consider this processInput function that uses typeof:


function processInput(input) {
if (typeof input === "string") {
console.log("PROCESSING YOUR STRING!");
} else if (typeof input === "number") {
console.log("PROCESSING YOUR NUMBER!");
} else {
console.log("PROCESSING YOUR OTHER DATA TYPE!");
}
}

Depending on what is passed into processInput, it will print out a different message:


processInput("hello"); // Output: PROCESSING YOUR STRING!
processInput(42); // Output: PROCESSING YOUR NUMBER!
processInput([1, 2, 3]); // Output: PROCESSING YOUR OTHER DATA TYPE!

Debugging with typeof

The final use case we'll look at for typeof is for debugging and troubleshooting code that's not working as expected. It can be really helpful just to figure out the type of a value.

Imagine we have a variable called annoyingProblematicVariable, and we expect it to be an array but trying to access the first value gives us some unexpected results:


annoyingProblematicVariable[0]
// Output: '['

To check the data type of annoyingProblematicVariable, you can simply run the typeof operator on it:


typeof annoyingProblematicVariable
// Output: 'string'

In this example, typeof tells us that annoyingProblematicVariable is a string, even though you were expecting it to be an array. Remember, if it were an array, typeof would return "object" instead.

Although this example is contrived, you might often use typeof with some mystery variable that you're expecting to be one data type, only to find out it's actually another data type.

For example, you might see a string when you forgot to parse JSON or convert a value to a number.

Wrap Up

While it's not perfect, the typeof operator can help you differentiate between objects, strings, and numbers. It will even tell you if a value is a function.

In addition to checking the data type of a value, you can use typeof to enforce typings within functions, handle various data types, and assist with debugging.

It's one of the essential tools in JavaScript!

Transcript

00:00 In this video, we're going to talk about JavaScript's typeof operator, a really powerful and commonly used tool that is sometimes misunderstood by beginners. So the first thing you need to know about typeof is that it does one thing. It helps us identify the data type of a given value. The next thing you need to know is that it's not a function.

00:19 So we spell it typeof, all lowercase, not like this, like a lot of other things in JavaScript. It's all lowercased, and it's an operator. So operators include things like the plus sign. The big difference here, aside from the fact that the plus sign does math, is that the plus sign expects two operands on the left and the right,

00:38 and then it returns some result, the sum of the two. Typeof is what's known as a unary operator, meaning it expects and it operates on a single operand, which we put after the word typeof. So after typeof, we can provide a value like 35.

00:55 I don't know why I'm sticking with 30s, but it's 32, 34, 35. And you can see it returns to me a string that contains the type of the value I provided. In this case, 35 is a number. You may see people sometimes do this with parentheses.

01:11 It's not going to cause a problem, but remember that it's not a function, and it's, in fact, an operator. So let's try a few more examples. If I do typeof on a number with a decimal point, it's still just considered number.

01:24 If I do it on a string like hello, it tells me typeof that is string. But let's try a few more complicated examples, and this is where it trips people up. If you try typeof on an array, it doesn't tell us array. It only tells us that it's of type object,

01:43 and this is because arrays are considered objects in JavaScript, and the same is true of an actual object. So if I have an object literal, just an empty pair of curly braces, that has the same value for typeof. It's the string object. Let's do another example. Here's a little bit trickier example.

02:02 This is a weird quirk in JavaScript. If you run typeof on the value null, null is considered an object basically because of a historical bug in JavaScript. So that's kind of a gotcha. It's not going to tell you that its typeof is null.

02:17 If I do typeof on the undefined value, that actually has a typeof undefined, and one more thing to know is if you do typeof not a number, that in fact has a value of number. So that's how it works. I didn't show an example of symbols. Let me just do one of Booleans real quick.

02:36 The typeof, the value false, is Boolean. Okay, so that's how it works. Next, let's talk about why you should care about it and why it gets used. The main reason is to do basic type checking and validation. So JavaScript is a dynamically typed language, meaning that a variable can hold any sort of value.

02:55 It can change data types. If I have x set to 23, I can change x to a string and then change it to a Boolean. JavaScript doesn't care. That's just the nature of JavaScript. But this dynamic typing can lead to all sorts of bugs. When you write code expecting one value or a type of a value

03:14 it gets a different type of value, and it's the whole reason tools like TypeScript exist, to enforce typings. So we can use a typeof operator to perform some basic type checking and validation to do something like this. A very simple example, a function called add. It expects two numbers. Well, it doesn't actually say two numbers. You could provide strings.

03:33 You could provide Booleans. You could provide objects. That's just how JavaScript works. However, in here we can use typeof to make sure that typeof a, the first argument, is a number, and typeof b, the second argument, is also a number. So both of these have to be true,

03:49 and then we can return a plus b using math, the plus sign operator. Otherwise, if one of those or both of those are not numbers, we'll throw an error. A very simple example, but let me demonstrate. If I add two numbers, it works just fine. If I make one of these a string, we get an error saying both arguments must be numbers.

04:08 Whereas before, if I didn't have this type checking in here and I simply returned a plus b, if I add two and the string d, I get some weird behavior. This is just what JavaScript does. When you try and add a number and a string, it concatenates them into a string.

04:26 So this is where type checking comes in handy. Presumably this is not the behavior I want from an add function. If it is, then I could leave it alone, but it's kind of unpredictable and weird. So I add this type checking in using typeof, and it makes sure that a and b are both numbers. Another way to use the typeof operator is in a conditional statement

04:45 to figure out the type of a given value and handle that value differently depending on its type. So instead of enforcing a single type and saying this add function only accepts numbers, I could write a very simple, trivial, useless function called processInput that expects some input value and then behaves differently

05:04 depending on the type of that value. And one thing I want to be very clear about, when you are making comparisons to the result of typeof, it always gives us a lowercased string as the result. So it's always lowercase number, for example, or Boolean.

05:20 So if you do something like typeof true equals equals Boolean spelled like this, it's not going to work. But if you do a lowercase b, that is in fact true because this is going to return the string Boolean with a lowercase b. So you just have to make sure you're matching that casing.

05:39 Okay, so back to this example. If our input type is a string, we'll print processing your string. If it's a number, we'll print processing your number. If it's something else, we'll print processing your other data type. So if I call processInput with a string, it tells me processing your string.

05:56 If I pass it in a number, processing your number, and if I give it an array, for example, which is of type typeof results in object, we get processing your other data type, a very simple example that doesn't actually do anything, but it demonstrates another way of using typeof.

06:12 The final use case for typeof that I'll demonstrate is in debugging, troubleshooting code that's not working the way you expect. It can be really useful just to figure out the type of a value. Often, bugs are traced down to a single value that is of the wrong type. Again, that's why languages or tools like TypeScript exist in the first place.

06:30 So I have this variable called annoyingProblematicVariable, and I'm expecting it to be an array. I want to access, let's say, the first value out of it, but it's giving me some weird result. This is not what I'm expecting. You don't have to know anything about what it's supposed to be, but let's just say it's wrong. I'm getting some weird result.

06:49 So what I could do is just simply run typeof on annoyingProblematicVariable, and it tells me that thing is a string, and I was expecting it to be an array. Now, if I was expecting it to be an array, remember, it wouldn't say array. It would return, the typeof operator would return object.

07:07 So this is a very contrived example, but often use typeof with some mystery variable. You're expecting it to be one thing, and then you'll find out, oh, it's actually a string. I forgot to parse this JSON, or I forgot to convert this to an object or convert this to a number or something like that. To wrap up, typeof is an operator.

07:24 It's a unary operator, and it's one of the essential tools in JavaScript that helps us identify data types. It's not perfect. It doesn't tell us if an array is an array. It tells us an array is an object, but it will help us differentiate between objects and strings and numbers. And one last thing I did not demonstrate is functions.

07:43 If I do typeof and then I have some function, just an empty function, it will tell me that thing is a function. You can use typeof to enforce typings in your functions, to enforce that arguments are numbers. You can use it to handle different data types, and you can use it to debug if you're unsure of the type of a given value.

More Tips