How to check if a javascript variable is an array ?

Published: February 14, 2022

Updated: December 09, 2022

Tags: Javascript; Array;

DMCA.com Protection Status

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 !'}