Yogesh Chauhan's Blog

How to Recognize an Array in JavaScript?

in JavaScript on 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.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
@mixin and @include in SCSS (Sass)SCSSUse SwiperJS to create mobile touch sliders fastMiscellaneousHigher Order Functions in JavaScript with ExamplesJavaScriptA quick introduction to API, REST API and PostmanMiscellaneousHow to create and store JSON objects in localStorage using JavaScript?JavaScriptWhat is Host Hardening and What are some Important Hardening Steps?MiscellaneousHow to enable GD library support for PHP on windows server?PHPSolution to “NullInjectorError: No provider for module” in Angular 9AngularTackle Accessibility in React with JSXReactWhat is the best way to add JavaScript Code into HTML?HTMLHow to apply style to a specific child element using CSS?CSSThe order Property in Flex Items in CSSCSS