How to check whether an array is a true array in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

In javascript, arrays are not true arrays. They are javascript objects. So when we try to know their type using typeof() operator the displayed output will be object.

Syntax

typeof(operand);

parameters - typeof() operator takes an operand and returns the data type of the operand. 

In the following example even though variable 'a' is an array, the typeof() operator returns the output as object because in general every array is an object.

Example

Live Demo

<html>
<body>
<script>
   var a = [1,2,5,"hello"];
   document.write(typeof(a));
   var b = {};
   document.write("</br>");
   document.write(typeof(b));
</script>
</body>
</html>

Output

object
object

Unlike typeof() operator, Array.isArray() checks whether the passed parameter is array or not. If the parameter is an array it gives out true as output else false as output.

Syntax

Array.isArray(array);

In the following example an array 'a' and an object 'b' were passed through Array.isArray() method. This method scrutinized them and displayed true and false as output respectively.

Example

Live Demo

<html>
<body>
<script>
   var a = [1,2,5,"hello"];
   var res1 = Array.isArray(a);
   document.write(res1);
   document.write("</br>");
   var b = {};
   var res2 = Array.isArray(b);
   document.write(res2);
</script>
</body>
</html>

Output

true
false
raja
Published on 27-Jun-2019 08:28:53
Advertisements