Skip to content
Fix Code Error

How do you check if a variable is an array in JavaScript?

March 13, 2021 by Code Error
Posted By: Anonymous

I would like to check whether a variable is either an array or a single value in JavaScript.

I have found a possible solution…

if (variable.constructor == Array)...

Is this the best way this can be done?

Solution

There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.

variable.constructor === Array

This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.

If you are having issues with finding out if an objects property is an array, you must first check if the property is there.

variable.prop && variable.prop.constructor === Array

Some other ways are:

Array.isArray(variable)

Update May 23, 2019 using Chrome 75, shout out to @AnduAndrici for having me revisit this with his question
This last one is, in my opinion the ugliest, and it is one of the slowest fastest. Running about 1/5 the speed as the first example. This guy is about 2-5% slower, but it’s pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

variable instanceof Array

This method runs about 1/3 the speed as the first example. Still pretty solid, looks cleaner, if you’re all about pretty code and not so much on performance. Note that checking for numbers does not work as variable instanceof Number always returns false. Update: instanceof now goes 2/3 the speed!

So yet another update

Object.prototype.toString.call(variable) === '[object Array]';

This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you’re looking for. However, since you’re looking for an array, just use the fastest method above.

Also, I ran some test: http://jsperf.com/instanceof-array-vs-array-isarray/35 So have some fun and check it out.

Note: @EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.

Answered By: Anonymous

Related Articles

  • Form field border-radius is not working only on the…
  • How to setup ember engines?
  • For-each over an array in JavaScript
  • Problems Installing CRA & NextJS from NPM…
  • Fastest way to list all primes below N
  • vuejs2 and chosen select issue
  • during wct test: Failed to load resource: the server…
  • How can I access and process nested objects, arrays or JSON?
  • How to handle Vue 2 memory usage for large data (~50…
  • Memcached vs. Redis?
  • Use of Jquery on scroll event
  • Ubuntu apt-get unable to fetch packages
  • What does "Fatal error: Unexpectedly found nil while…
  • Is there any "font smoothing" in Google Chrome?
  • Why does git perform fast-forward merges by default?
  • Triggering change doesn't update vuejs binding
  • The definitive guide to form-based website authentication
  • LDAP root query syntax to search more than one specific OU
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Manually adding a Userscript to Google Chrome
  • Fastest way to iterate over all the chars in a String
  • AppCompat v7 r21 returning error in values.xml?
  • How does PHP 'foreach' actually work?
  • What does do?
  • Smart way to truncate long strings
  • Get the name of an object's type
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • data.table vs dplyr: can one do something well the…
  • C threads corrupting each other
  • How to detect Safari, Chrome, IE, Firefox and Opera browser?
  • What are the nuances of scope prototypal /…
  • How to generate a random string of a fixed length in Go?
  • What is causing this broken animation/transition in…
  • Google Chromecast sender error if Chromecast…
  • Run chrome in fullscreen mode on Windows
  • Simplest way to create Unix-like continuous pipeline…
  • How to compare arrays in JavaScript?
  • Best practice multi language website
  • Understanding PrimeFaces process/update and JSF…
  • JavaScript hashmap equivalent
  • Debugging Javascript (Backbone and Marionette)
  • Jquery Chosen plugin - dynamically populate list by Ajax
  • Is this very likely to create a memory leak in Tomcat?
  • How do I reset a jquery-chosen select option with jQuery?
  • Clear and refresh jQuery Chosen dropdown list
  • What is a NullReferenceException, and how do I fix it?
  • What is your most productive shortcut with Vim?
  • Super slow preflight OPTIONS in Chrome only
  • What is an IndexOutOfRangeException /…
  • Dead simple example of using Multiprocessing Queue,…
  • Vue CLI 3 / Webpack production build not working on…
  • aurelia - dropdown not selecting value from db on load
  • Usage of __slots__?
  • Merge, update, and pull Git branches without using checkouts
  • How do I include a JavaScript file in another…
  • Is JavaScript guaranteed to be single-threaded?
  • Start redis-server with config file
  • Changing selection in a select with the Chosen plugin
  • Logging best practices
  • TypeError: Cannot read property 'webpackJsonp' of undefined
  • How do I return the response from an asynchronous call?
  • C++ template,typename and operator
  • What is an optional value in Swift?
  • What are the undocumented features and limitations…
  • Difference between variable declaration syntaxes in…
  • java.sql.SQLException: - ORA-01000: maximum open…
  • What is the copy-and-swap idiom?
  • How do I iterate over an NSArray?
  • Jquery chosen remove attributes by name or id
  • commandButton/commandLink/ajax action/listener…
  • using d3.js with aurelia framework
  • How can I find the product GUID of an installed MSI setup?
  • How should a model be structured in MVC?
  • Android- Error:Execution failed for task…
  • What are the real-world strengths and weaknesses of…
  • How to "properly" create a custom object in JavaScript?
  • What is the best practice for creating a favicon on…
  • jQuery Mobile: document ready vs. page events
  • configure: error: C compiler cannot create executables
  • Ember.js - Managing Asynchronous Events & Callbacks
  • Getting Chrome to prompt to save password when using…
  • How do I extract data from JSON with PHP?
  • Switch statement for greater-than/less-than
  • OpenAPI path/query parameters nested structure serialization
  • Use a content script to access the page context…
  • Identifying and solving…
  • Creating a singleton in Python
  • What is WebKit and how is it related to CSS?
  • How is TeamViewer so fast?
  • Fastest way to duplicate an array in JavaScript -…
  • What is the maximum length of a URL in different browsers?
  • Why not use tables for layout in HTML?
  • When to use MyISAM and InnoDB?
  • Cloud functions/Firestore. How to trigger when the…
  • How can I manually compile a svelte component down…
  • How do I use arrays in C++?
  • Most efficient way to increment a Map value in Java
  • How does data binding work in AngularJS?
  • Database development mistakes made by application developers
  • SQL Server: Query fast, but slow from procedure

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to convert a string to lower case in Bash?

Next Post:

Convert form data to JavaScript object with jQuery

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error