How to check if a javascript variable is an array ?

Active February 14, 2022    /    Viewed 174    /    Comments 0    /    Edit


Example of how to check if a javascript variable is an array:

Using Array.isArray()

A solution to check if a javascript variable is an array is to use Array.isArray()

var data = [1,2,3,4];

Array.isArray(data);

returns here

true

while

data = 3;

returns

False

With a if statement

var data = [1,2,3,4];

if (!Array.isArray(data)) { console.log('oups, not an array') };

returns nothing.

However

data = 3;

if (!Array.isArray(data)) { console.log('oups, not an array') };

returns

oups, not an array

Using console.assert()

Another solution to debug a code is to use console.assert()

console.assert( Array.isArray(data), {errorMsg: 'Warning: not an array !'} );

Here it will return nothing since data is an array,

Now if we change data variable to:

data = 'Hello World';

then

console.assert( Array.isArray(data), {errorMsg: 'Warning: not an array !'} );

will returns the folling error message:

Assertion failed: {errorMsg: 'Warning: not an array !'}

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount