how.wtf

Check if a variable is an array in JavaScript

· Thomas Taylor

In TypeScript or JavaScript, checking if a variable is an array can be completed in two ways.

Using the Array.isArray()

Using the native Array.isArray() method, a boolean will be returned.

1const names = ["sally", "billy", "mary"];
2const notAnArray = 'str';
3console.log(Array.isArray(names)); // true
4console.log(Array.isArray(notAnArray)); // false

Using the instanceOf operator

As an alternative option, instanceOf will yield the same results.

1const names = ["sally", "billy", "mary"];
2const notAnArray = 'str';
3console.log(names instanceof Array); // true
4console.log(notAnArray instanceof Array); // false

#Javascript  

Reply to this post by email ↪