J

JavaScript Handbook

Clean • Professional

JavaScript Type Operators

1 minute

Type Operators

Type operators are used to check the type of a variable or object.

The two main type operators in JavaScript are:

  1. typeof
  2. instanceof

typeof Operator

  • Returns a string indicating the type of a variable or value.

    Syntax:

typeof operand

Examples:

console.log(typeof 42); // "number"
console.log(typeof 'Hello'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof { name: 'John' }); // "object"
console.log(typeof [1, 2, 3]); // "object"
console.log(typeof function(){}); // "function"
console.log(typeof null); // "object" (this is a known quirk in JS)

instanceof Operator

  • Checks whether an object is an instance of a specific class or constructor.
  • Returns true or false.

Syntax:

object instanceof constructor

Examples:

let arr = [1, 2, 3];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true

let date = new Date();
console.log(date instanceof Date); // true
console.log(date instanceof Object); // true

function Person(name) {
  this.name = name;
}
let p = new Person('John');
console.log(p instanceof Person); // true
console.log(p instanceof Object); // true

 

Article 0 of 0