JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript typeof

8 April 2025 | Category:

The typeof operator in JavaScript is used to check the data type of a variable or value. It returns a string indicating the type.


✅ Syntax:

typeof operand

OR

typeof(operand)

🔢 Common Examples

typeof "Hello"     // "string"
typeof 42          // "number"
typeof true        // "boolean"
typeof undefined   // "undefined"
typeof { name: "Ali" } // "object"
typeof [1, 2, 3]   // "object"
typeof null        // "object" ❗ (known quirk)
typeof function() {} // "function"

📘 typeof Results Table

Valuetypeof Result
"Hello""string"
123"number"
true / false"boolean"
undefined"undefined"
{} (object literal)"object"
[] (array)"object"
null"object" ❗
function() {}"function"
Symbol("id")"symbol"
BigInt(1234567890123456789)"bigint"

⚠️ Important Notes

1. ❗ typeof null returns "object"

This is a known bug in JavaScript that exists for backward compatibility.

typeof null; // "object" (even though it's null)

You can check for null more reliably using:

value === null

2. Arrays return "object"

Even though arrays are different from plain objects:

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

To specifically check for arrays, use:

Array.isArray([1, 2, 3]); // true

🔎 Checking Multiple Types

You can use typeof inside conditionals:

function checkType(val) {
  if (typeof val === "string") {
    console.log("This is a string.");
  } else if (typeof val === "number") {
    console.log("This is a number.");
  } else {
    console.log("Unknown type.");
  }
}

🧪 Real-world Example

const inputs = [42, "hello", true, null, undefined, [1, 2], {}, () => {}];

inputs.forEach(item => {
  console.log(`${item} => ${typeof item}`);
});

✅ Summary

  • typeof returns a string indicating the type of a value.
  • Useful for debugging and type checking.
  • Be aware of quirks like:
    • typeof null → "object"
    • typeof array → "object"