JavaScript typeof

The typeof operator returns a string indicating the type of a given value. It's useful for debugging and type checking, ensuring that variables hold expected data types.

Key Topics

Basic Usage

Use typeof variable to determine its type.

console.log(typeof 42);
console.log(typeof "Hello");
console.log(typeof true);
console.log(typeof {});
console.log(typeof null);

Output

> "number"

> "string"

> "boolean"

> "object"

> "object"

Explanation: Numbers, strings, and booleans reflect their types. Objects return "object", and note that null is an "object" due to a historical quirk.

Common Types

Types include: "number", "string", "boolean", "object", "function", "undefined", and "symbol".

Typeof Quirks

typeof null returns "object" for legacy reasons. Also, arrays are "object" type.

JavaScript Usage in DOM

Use typeof to validate user input types or ensure certain variables are objects before manipulating DOM elements based on their data.

<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>typeof in DOM</title></head>
<body>
    <h1>typeof Demo</h1>
    <input type="text" id="inputVal" placeholder="Enter something">
    <button onclick="checkType()">Check Type</button>
    <p id="result"></p>

    <script>
        function checkType() {
            let val = document.getElementById("inputVal").value;
            document.getElementById("result").textContent = "Type: " + typeof val;
        }
    </script>
</body>
</html>

Key Takeaways

  • typeof: Returns a string representing a value's type.
  • Common Types: "number", "string", "boolean", "object", etc.
  • Quirks: null and arrays return "object".
  • DOM Integration: Validate and handle variables before manipulating DOM elements.