AppDividend
Latest Code Tutorials

Javascript Array isArray Tutorial With Example | Array.isArray() Function

0

Javascript Array isArray Tutorial With Example is today’s topic. The Array.isArray() method determines whether the passed value is an Array. If the value is an Array, then true is returned; otherwise, false is return. When checking for the Array instance, the Array.isArray is preferred over the instanceof because it works through iframes.

Javascript Array isArray

See the syntax of isArray() function.

Array.isArray(value)

The value to be checked.

See the following example.

// app.js

let arr = ['Millie', 'Bobby', 'Brown'];
console.log(Array.isArray(arr))

let data = {
  realname: 'Millie Bobby Brown',
  character: 'Eleven',
  series: 'Stranger Things'
};
console.log(Array.isArray(data));

In the above example, we have defined an array of Strings and an array of Objects.

See the following output.

➜  es git:(master) ✗ node app
true
false
➜  es git:(master) ✗

#Javascript isArray behavior with different types

TYPE VALUE AS JSON ARRAY.ISARRAY
Empty Array [] true
An array of Number literal [1,2,3] true
An array of String literal [“a” “b”, “c”] true
Array (using constructor.from) [null,null,null,null,null,null,null,null,null,null] true
Array with empty values using constructor [null,null,null,null,null,null,null,null,null,null] true
Array with values using constructor [1,2,3] true
Array prototype [] true
Array from another window [1,2,3] true
Empty Object {} false
Object with .length property {“length”:10} false
Object whose __prototype__ is Array {} false
Object {“a”: “2”, “b”: “c”} false
Object with nested Array {“nested”:[“2”, “c”]} false
Empty Set {} false
Set of String {} false
Set of Number {} false
Empty Map {} false
Map with different types {} false
String literal “hello world.” false
String Object “hello world” false
Boolean true literal true false
Boolean false literal false false
Explicitly undefined undefined false
Implicit undefined undefined false
null null false
Number (integer) 123 false
Number (float) 1.23 false

An array can be checked if it is empty by using the array.length property. This property returns several elements in the array.

If the number is greater than 0, it evaluates to true.

This method and property can be both used together with the AND(&&) operator to determine whether the array exists and is not empty.

Array isArray() Polyfill

Running the following code before any other code will create Array.isArray() if it’s not natively available in your browser.

if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

Finally, Javascript Array isArray Tutorial With Example | Array.isArray() Function is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.