Often you need to check if the variable is an array or not. There are many solutions available in javascript but the simplest one is using Array.isArray() method.
Using Array.isArray method in JavaScript
The function Array.isArray() expects one argument which will be the variable and returns true or false depending on the type.
Here is a simple example of using Array.isArray() method in javascript.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const name = "John"; const age = 22; const subjects = ["Computer Science", "Mathematics", "Engineering"]; // Testing with Array.isArray() method console.log(Array.isArray(name)); // output: false console.log(Array.isArray(age)); // output: false console.log(Array.isArray(subjects)); // output: true |
The output for the first and second console.log will be false but true for the third. As you can see the subjects is an array type, with Array.isArray() we have tested it.
Please check mozilla documentation for more information and browser compatibility about Array.isArray() method.
Conclusion
Array.isArray() is a useful method to check if the variable is an array or not. This method will return true or false depending on the variable passed as a parameter.