typeof operator in Javascript

  • In JavaScript, the typeof keyword is used to determine the data type of a given value. It returns a string that indicates the type of the value, such as "string", "number", "boolean", "object", "function", or "undefined".

The typeof keyword can be used in several ways:

  • To determine the type of a variable or value:

    let str = "Hello, world!";
    let num = 42;
    let bool = true;

    console.log(typeof str); // Output: "string"
    console.log(typeof num); // Output: "number"
    console.log(typeof bool); // Output: "boolean"

  • To check if a variable is defined:

        let foo;
        console.log(typeof foo); // Output: "undefined"

  • To check if a value is a function:

    function bar() {
        return "Hello, world!";
    }

    console.log(typeof bar); // Output: "function"

  • To check if a value is an object:

    let obj = { name: "John", age: 30 };
    console.log(typeof obj); // Output: "object"

  • To check if a value is null:

    let n = null;
    console.log(typeof n); // Output: "object"

  • Note that the typeof keyword returns "object" for null values, which is a quirk of JavaScript.
  • In general, the typeof keyword is a useful tool for checking the data type of a given value in JavaScript. It can be used to determine how to process a value or to handle unexpected data types in a program. However, it's important to be aware of its limitations and quirks, such as the fact that it returns "object" for null values.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...