![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check if a variable is an array in JavaScript?
In javascript we can check whether a variable is array or not by using three methods.
1) isArray() method
The Array.isArray() method checks whether the passed variable is array or not. If the variable is an array it displays true else displays false.
Syntax
Array.isArray(variableName)
Example
<html> <body> <script type="text/javascript"> arr = [1,2,3,4,5]; str = "i love my india"; document.write( Array.isArray(arr)); document.write("</br>"); document.write( Array.isArray(str)); </script> </body> </html>
Output
true false
2) instanceof operator
The instanceof operator is used to test whether the prototype property of a constructor appears anywhere in the prototype chain of an object. In the following example the instanceof operator checks whether there exists an array prototype.
Syntax
variable instanceof Array
Example
<html> <body> <script type="text/javascript"> arr = [1,2,3,4,5]; str = "i love my india"; document.write(str instanceof Array); document.write("</br>"); document.write(arr instanceof Array); </script> </body> </html>
Output
false true
3) Checking the constructor property of the variable
It displays true when the variable is same as what we specified. Here we specified that the variable should be array. So when the variable is array this method displays true else displays false.
Syntax
variable.constructor === Array
Example
<html> <body> <script type="text/javascript"> arr = [1,2,3,4,5]; str = "i love my india"; document.write(str.constructor === Array); document.write("</br>"); document.write(arr.constructor === Array); </script> </body> </html>
Output
false true
Advertisements