YogeshChauhan.com
How to Recognize an Array in JavaScript?
December 3, 2020

The problem is that the JavaScript operator typeof returns “object”:


var numbers = [2, 3, 4]; 

typeof numbers;

//object

Why?

As we have already seen in this post, JavaScript Arrays: A Separate Data Type Or Objects?JavaScript arrays are objects.

Method 1

We can use Array.isArray() method which was introduced in ECMAScript 5.


var numbers = [2, 3, 4]; 

Array.isArray(numbers);

// true

👎 This method is not supported in older browsers.

Method 2

We can make a our function and use constructor property to know whether it’s an array.


var numbers = [2, 3, 4]; 

function isArray(x) {
  return x.constructor.toString().indexOf("Array") > -1;
}

isArray(numbers);

// true

Let’s understand it.

The constructor property returns an array’s constructor function:


var numbers = [2, 3, 4]; 

console.log(numbers.constructor);

// [Function: Array]

which we convert to a string and get the index of word “Array”. If it’s the array then the word “array” will be there and will return positive value.

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?



Recently Posted

Feb 27 WordPress: How to display slider repeater fields in ACF? Feb 26 Simple Page Hit Counter in PHP Feb 26 Here’s what we can do with PHP date() function Feb 25 How to set default timezone using PHP? Feb 24 WordPress: How to loop through a repeater field in ACF? Feb 24 How to get ACF values from custom post type?



You might also like these

Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software”MiscLearn to Implement Estimated Reading Time using PHP Part 2: Final Implementation with Source CodePHPWhat is HTMLUnknownElement?HTMLHow to Access a Global Variable From Inside a Function in PHP?PHPHow to concatenate variable with string in Swift?SwiftAttributes and Properties in JavaScript and HTMLHTML4 ways to create Date Objects in JavaScriptJavaScriptHow to Draw a Circle in HTML5 Using Canvas Tag?HTMLHow to make WordPress main stylesheet (style.css)?WordPress3 Common Usability Mistakes In Web DesignUI/UXHow can one check to see if a remote file exists using PHP?PHPPHP Login System using PDO Part 1: Create User Registration PagePHP