How to use typeof operator?

The typeof operator in JavaScript is used to determine the type of a given value. It returns a string indicating the type of the unevaluated operand. Here’s a concise breakdown of how to use it:

Syntax

typeof operand

Common Usage

Here are some examples of how to use the typeof operator:

console.log(typeof "Hello, world!"); // Output: "string"
console.log(typeof 42);                // Output: "number"
console.log(typeof true);              // Output: "boolean"
console.log(typeof undefined);         // Output: "undefined"
console.log(typeof null);              // Output: "object" (this is a known quirk in JavaScript)
console.log(typeof Symbol("sym"));     // Output: "symbol"
console.log(typeof { name: "Alice" }); // Output: "object"
console.log(typeof [1, 2, 3]);         // Output: "object" (arrays are also objects)

Checking Specific Types

You can use typeof in conditional statements to check for specific types. For example:

const value = 10;

if (typeof value === "number") {
    console.log("The value is a number.");
} else {
    console.log("The value is not a number.");
}

Summary

The typeof operator is a powerful tool for type checking in JavaScript, helping you ensure that your variables are of the expected type before performing operations on them.

If you want to practice using typeof and other JavaScript concepts, consider exploring interactive coding platforms or tutorials that focus on JavaScript fundamentals. Let me know if you have any further questions!

0 Comments

no data
Be the first to share your comment!