How to use typeof in if statement in JavaScript?

Learn how to use the typeof operator within an if statement in JavaScript to check the type of a value before performing an operation on it.

This article provides clear explanations and examples to help you master and understand this powerful feature of the language.

So bear with us as we will hand you the different ways to use the typeof in if statement in JavaScript and other uses of typeof as well.

What is typeof in JavaScript?

The typeof operator is a keyword in JavaScript that returns a string indicating the type of the operand’s value.

It can be used to determine the data type of a variable or expression.

For instance, typeof 18 returns “number,” typeof “itsourceccode” returns “string,” and typeof true returns “boolean.”

The typeof operator can also be used to check if a variable is defined or not.

For example, typeof sampleVar returns “undefined” if the variable sampleVar has not been declared or assigned any value.

The possible return values of typeof are: “undefined,” “object,” “boolean,” “number,” “bigint,” “string,” “symbol,” and “function.”

One thing to keep in mind that typeof null returns “object,” which can be confusing. This is due to the way JavaScript was originally implemented and is considered a historical accident

Syntax

typeof operand

Parameter

📌operand

The expression or variable to evaluate.

Return value

A string indicating the type of the operand’s value. The possible return values are:

Undefined

Object

Boolean

Number

✅ bigint

✅ String

✅ Symbol

✅ Function

5 different data types that can contain values

📌boolean

📌function

📌number

📌object

📌string

6 types of objects

📌Array

📌 Boolean

📌Date

📌Number

📌Object

📌String

2 data types that cannot contain values

📌null

📌undefined

How to use typeof in if statement JavaScript?

You can use the typeof operator within an if statement to check the type of a value before performing an operation on it.

For example, you can use if (typeof x === “number”) { … } to check if the variable x contains a number before performing a calculation on it.

Here are some different ways you can use the typeof operator within an if statement in JavaScript:

Checking for a specific type

let x = 15;

if (typeof x === "number") {
console.log(x + 1); 
} else {
console.log("x is not a number");
}

In this example, we use the typeof operator to check if the variable x contains a value of a specific type, in this case, a number.

If x is a number, we add 1 to it and log the result to the console. If x is not a number, we log a message to the console indicating that it’s not a number.

Output:

16

Checking for multiple types

let x = "Hi, Welcome to Itsourcecode!";

if (typeof x === "string" || typeof x === "number") {
console.log(x);
} else {
console.log("x is not a string or a number");
}

Here, we use the typeof operator to check if the variable “x” contains a value of one of several types, in this case, either a string or a number.

If “x” is either a string or a number, we log its value to the console. If “x” is neither a string nor a number, we log a message to the console indicating that it’s not one of the expected types.

Output:

Hi, Welcome to Itsourcecode!

Using a switch statement to handle multiple types

let x = true;

switch (typeof x) {
    case "string":
        console.log("x is a string");
        break;
    case "number":
        console.log("x is a number");
        break;
    case "boolean":
        console.log("x is a boolean");
        break;
    default:
        console.log("x is of an unknown type");
}

In here, we use the typeof operator within a switch statement to handle multiple types. We check the type of the variable “x” and use different cases to handle different types.

For example, if “x” is a string, we log a message indicating that it’s a string. If “x” is a number, we log a message indicating that it’s a number.

If “x” is neither of these types, we log a message indicating that it’s of an unknown type.

Output:

x is a boolean

Examples of typeof in different usage

Booleans

typeof true === "boolean";
typeof false === "boolean";
typeof Boolean(1) === "boolean"; // Boolean() will convert values based on if they're truthy or falsy
typeof !!1 === "boolean"; // two calls of the ! (logical NOT) operator are equivalent to Boolean()

Functions


typeof function () {} === "function";
typeof class C {} === "function";
typeof Math.sin === "function";

Numbers

typeof 18 === "number";
typeof 1.5 === "number";
typeof Math.LN2 === "number";
typeof Infinity === "number";
typeof NaN === "number"; // Despite being "Not-a-Number"
typeof Number("1") === "number"; // Number tries to parse things into numbers
typeof Number("shoe") === "number"; // including values that cannot be type coerced to a number
typeof 42n === "bigint";

Objects


typeof { a: 1 } === "object";

// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

Strings

typeof "" === "string";
typeof "Itsourcecode" === "string";
typeof `template literal` === "string";
typeof "16" === "string"; // note that a number within a string is still typeof string
typeof typeof 1 === "string"; // typeof always returns a string
typeof String(1) === "string"; // String converts anything into a string, safer than toString

Symbols

typeof Symbol() === "symbol";
typeof Symbol("foo") === "symbol";
typeof Symbol.iterator === "symbol";

The following are confusing that needs to avoid

typeof new Boolean(true) === "object";
typeof new Number(1) === "object";
typeof new String("abc") === "object";

Undefined

typeof undefined === "undefined";
typeof declaredButUndefinedVariable === "undefined";
typeof undeclaredVariable === "undefined";

Conclusion

In conclusion, this article provides a clear explanation of the typeof operator in JavaScript and its practical use within an if statement.

The typeof operator is a powerful tool to determine the data type of a variable or expression. It can be used to check if a variable is defined or not, and it returns a string representing the type of the operand’s value.

This article covers different examples of using typeof within if statements to check for specific types or handle multiple types using a switch statement. Also, we present examples of different data types, objects, and scenarios where typeof can be used.

We are hoping that this article provides you with enough information that helps you understand the typeof Javascript.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Leave a Comment