Array isArray() method with example in JavaScript

JavaScript isArray() method: Here, we are going to learn about the isArray() method of array in JavaScript.
Submitted by IncludeHelp, on February 27, 2019

JavaScript isArray() method

isArray() method is used to check whether a given object is an array or not. It returns true if an object is an array; else it returns false.

Syntax:

    Array.isArray(object_name);

It accepts an object and returns true or false.

Examples:

    Input:
    var arr1 = [10, 20, 30, 40, 50];

    Function call:
    Array.isArray(arr1);
    
    Output:
    true 

    Input:
    var a = 10;

    Function call:
    Array.isArray(a);
    
    Output:
    false

JavaScript Code to check whether an object is an array or not

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>
		var arr1 = [10, 20, 30, 40, 50];
		var arr2 = ["Amit", "Ankur", "Akash"];
		var arr3 = [];
		var a = 10;
		
		document.write("arr1: " + Array.isArray(arr1) + "<br>");
		document.write("arr2: " + Array.isArray(arr2) + "<br>");
		document.write("arr3: " + Array.isArray(arr3) + "<br>");
		document.write("a: " + Array.isArray(a) + "<br>");		
		
		//checking
		if(Array.isArray(arr1))
			document.write("arr1 is an array<br>");
		else
			document.write("arr1 is not an array<br>");
		
		if(Array.isArray(arr2))
			document.write("arr2 is an array<br>");
		else
			document.write("arr2 is not an array<br>");
			
		if(Array.isArray(arr3))
			document.write("arr3 is an array<br>");
		else
			document.write("arr3 is not an array<br>");
			
		if(Array.isArray(a))
			document.write("a is an array<br>");
		else
			document.write("a is not an array<br>");
	</script>
</body>
</html>

Output

arr1: true
arr2: true
arr3: true
a: false
arr1 is an array
arr2 is an array
arr3 is an array
a is not an array

JavaScript Array Object Methods »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.