Understanding the typeof Operator in JavaScript

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



The typeof Operator

Syntax:

Syntax

typeof operand
            

Possible Return Values:

  • 'string'
  • 'number'
  • 'boolean'
  • 'undefined'
  • 'object'
  • 'function'
  • 'symbol' (introduced in ES6)

Example Usage

Example Code

let num = 10;
let str = "hello";
let bool = true;
let obj = {};
let func = function() {};
let undef; // Variable declared but not assigned

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

console.log(typeof func);  // Output: "function"
console.log(typeof undef); // Output: "undefined"
            
Output

number
string
boolean
object
function
undefined
            

Important Considerations

  • typeof null returns "object", which is a known JavaScript quirk.
  • Arrays are considered objects in JavaScript, so typeof an array will also return "object".
  • Custom objects and instances of classes will also return "object". To differentiate between different object types, you might need to use other methods like instanceof or Object.prototype.toString.call().

Using typeof Effectively

  • Type Checking: Determine the data type of a value before performing operations.
  • Conditional Logic: Make decisions based on the type of a value.
  • Debugging: Identify unexpected data types.

Example:

Example Code

function processValue(value) {
  if (typeof value === "number") {
    console.log("It's a number");
  } else if (typeof value === "string") {
    console.log("It's a string");
  } else {
    console.log("Unknown type");
  }
}
            

Conclusion

By understanding how to use the typeof operator, you can write more robust and reliable JavaScript code.