JS Coding Questions Logo
JS Coding Questions
#441💼 Interview💻 Code

How to verify if a variable is an array?

Advertisement

728x90

It is possible to check if a variable is an array instance using 3 different ways,

1. Array.isArray() method:

The Array.isArray(value) utility function is used to determine whether value is an array or not. This function returns a true boolean value if the variable is an array and a false value if it is not.

javascript
1const numbers = [1, 2, 3];
2  const user = { name: "John" };
3  Array.isArray(numbers); // true
4  Array.isArray(user); //false

2. instanceof operator:

The instanceof operator is used to check the type of an array at run time. It returns true if the type of a variable is an Array other false for other type.

javascript
1const numbers = [1, 2, 3];
2  const user = { name: "John" };
3  console.log(numbers instanceof Array); // true
4  console.log(user instanceof Array); // false

3. Checking constructor type:

The constructor property of the variable is used to determine whether the variable Array type or not.

javascript
1const numbers = [1, 2, 3];
2  const user = { name: "John" };
3  console.log(numbers.constructor === Array); // true
4  console.log(user.constructor === Array); // false

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 12

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
441of476