JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to check if a variable is an array in JavaScript?

If you want to check if a variable is an array, then use the instanceof operator.

The instanceof operator is a binary operator and expects two operands. First, on the left-hand side of the instanceof operator, specify the variable you want to check, and on the right-hand side, mention Array. If the variable is an array, then the instanceof operator evaluates to true otherwise false.

variable instanceof Array

The following example shows how to check if a variable is an array or not:

let x = [1, 2, 3, 4, 5];
let y = "JavaScript";
console.log(x instanceof Array); //true
console.log(y instanceof Array); //false

You mainly use the instanceof operator in an if condition to check whether a variable is an array or not.

let x = [1, 2, 3, 4, 5];
if(x instanceof Array){
  console.log("x is an array");
}else{
  console.log("x is not an array");
}

Why typeof array is object in JavaScript?

typeof array is object because an array is a reference type, and the typeof operator returns "object" for non-primitive values such as array, object, etc.

It is essential to understand that the typeof operator is mainly used for finding out the data type of a primitive variable. The best way to check if a variable is an array is to use the instanceof operator.

let x = [1, 2, 3, 4, 5];
console.log(typeof x); //"object"
console.log(x instanceof Array); //true

Recommended Posts