JavaScript Introduction | Standard Objects | Array Object
In JavaScript, an array is defined as an ordered collection of values and is handled as an Array object.
Array Methods
JavaScript provides various methods so users can easily perform array-related tasks. Array methods are methods defined on the Array object and used for operations related to arrays.
- Array.isArray()
- Array.from()
- Array.of()
Array.isArray() Method
The Array.isArray() method checks whether the value passed to it is an Array object.
Array.isArray([]); // true
Array.isArray(new Array()); // true
Array.isArray(123); // false
Array.isArray("Array"); // false
Array.isArray(true); // false
Array.from() Method
The Array.from() method, added in ECMAScript 6, converts the following objects as if they were arrays.
- Array-like objects: objects that have a
lengthproperty and indexed elements - Iterable objects: objects whose elements can be individually selected, such as
Map,Set, and strings
Strictly speaking, however, the object created this way is not exactly an Array object, but a child class of the Array object.
function arrayFrom() {
return Array.from(arguments);
}
Array.from(arrayFrom(1, 2, 3)); // [1, 2, 3]
var myMap = new Map([[1, 2], [3, 4]]);
Array.from(myMap); // [1, 2, 3, 4]
Array.from("JavaScript"); // [J,a,v,a,S,c,r,i,p,t]
The Array.from() method is supported only in Firefox 32.0 and later.
Array.of() Method
The Array.of() method, added in ECMAScript 6, creates a new Array instance from the values passed as arguments, regardless of the number or type of arguments. The difference between Array.of() and the Array object constructor is how an integer argument is handled.
new Array(10); // [,,,,,,,,,] -> Creates an empty array with 10 array elements.
Array.of(10); // [10] -> Creates an array with one array element, the number 10.
In the example above, if the integer 10 is passed as an argument to the Array object constructor, the constructor creates an empty array with a length of 10. However, if the integer 10 is passed as an argument to Array.of(), it creates an array with length 1 whose array element is the integer 10.
The Array.of() method is not supported in Internet Explorer, Opera, or Safari.