Learn how to perform type checking in JavaScript using typeof and instanceof operators.

JavaScript is a loosely-typed language, so there is no restriction on the variable’s type.

For example, if you’ve created a variable with a string type, later you can assign to the same variable a number:

let message = 'Hello'; // assign a string

message = 14; // assign a number

Such dynamism gives you flexibility and simplifies variables declaration.

On the other side, you can never be sure that a variable contains a value of a certain type. For example, the following function greet(who) expects a string argument, however, you can invoke the function with any type of argument:

function greet(who) {
  return `Hello, ${who}!`
}

greet('World'); // => 'Hello, World!'
// You can use any type as argument
greet(true);    // => 'Hello, true!'
greet([1]);     // => 'Hello, 1!'

That’s why, sometimes, you need to check the variable’s type in JavaScript — using typeof operator, as well as instanceof to check instance types.

Let’s see in more detail how to use typeof and instanceof operators in JavaScript.

  • typeof operator
    • typeof null
    • typeof and not defined variables
  • instanceof operator
    • instanceof and the parent class

#javascript #web-development #testing #programming

Type checking in JavaScript: Typeof and Instanceof Operators
1.65 GEEK