How to determine if a value is an array in JavaScript
The Array.isArray(value) method allows you to determine if the value passed is an array.
const names = ['Bill', 'Ben', 'Beth'];
Array.isArray(names);
// true
Array.isArray('Brian');
// false
Array.isArray(undefined);
// false
Array.isArray([]);
// true
A good real world use case for this method is checking if the argument passed to a function is an array. This can be used to guard against parameters not suitable for the function. The example function below accepts an array of tableNames to be deleted but returns early with a message in the console if the parameter is not an array.
function clearTables(tableNames) {
if (Array.isArray(tableNames)) {
console.log('tableNames must be an array.');
return;
}
tableNames.forEach((name) => {
clearTableByName(name);
console.log(`${name} successfully cleared`);
});
}
clearTables(['table1', 'table2']);
// table1 successfully cleared
// table2 successfully cleared
clearTables('table1');
// tableNames must be an array.