JavaScript Type operators


Type operators in JavaScript are used to determine or interact with the type of a value or variable. They help you check types, identify instances of classes or objects, and more. Here’s a detailed look at the main type operators:

1. typeof Operator

  • Purpose: Returns a string indicating the type of a variable or expression.
  • Syntax: typeof operand
  • Example:
    let num = 42; console.log(typeof num); // 'number' let str = 'Hello'; console.log(typeof str); // 'string' let obj = {}; console.log(typeof obj); // 'object' let arr = [1, 2, 3]; console.log(typeof arr); // 'object' (arrays are objects in JavaScript) let func = function() {}; console.log(typeof func); // 'function' let und; console.log(typeof und); // 'undefined'

2. instanceof Operator

  • Purpose: Tests whether an object is an instance of a specific constructor or class.

  • Syntax: object instanceof constructor

  • Example:

    let arr = [1, 2, 3]; console.log(arr instanceof Array); // true let date = new Date(); console.log(date instanceof Date); // true let obj = {}; console.log(obj instanceof Object); // true
    • Note: instanceof checks the prototype chain, so it can determine if an object was created from a specific constructor or class.

3. Array.isArray() Method

  • Purpose: Determines whether a value is an array. This is a built-in method rather than an operator, but it's commonly used for type checking.
  • Syntax: Array.isArray(value)
  • Example:
    let arr = [1, 2, 3]; console.log(Array.isArray(arr)); // true let str = 'Hello'; console.log(Array.isArray(str)); // false

4. typeof with Null Values

  • Note: typeof returns "object" for null, which is considered a historical bug in JavaScript.
  • Example:
    let n = null; console.log(typeof n); // 'object'

Key Points:

  • Primitive Types: typeof can distinguish between primitive types like number, string, boolean, undefined, and symbol.
  • Objects and Functions: typeof returns "object" for objects and arrays (since arrays are a type of object) and "function" for functions.
  • Instance Checking: instanceof is useful for checking if an object was created by a specific constructor or class, and is handy for custom types and inheritance hierarchies.