Active February 14, 2022 / Viewed 167 / Comments 0 / Edit
Example of how to check if a javascript variable is an array:
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
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
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 !'}
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!