JavaScript features a built-in array constructor, new Array().
However, using []is considered safer and more concise.
Both statements below achieve the same outcome, generating a new empty array named “points”:
const points = new Array(); const points = []; |
Both of these distinct statements generate a new array consisting of 6 numbers:
const points = new Array(40, 100, 1, 5, 25, 10); const points = [40, 100, 1, 5, 25, 10]; |
The use of the new keyword can lead to unexpected outcomes:
// Create an array with three elements: const points = new Array(40, 100, 1); |
// Create an array with two elements: const points = new Array(40, 100); |
// Create an array with one element ??? const points = new Array(40); |
A Common Error
const points = [40]; |
differs from:
const points = new Array(40); |
// Create an array with one element: const points = [40]; |
// Create an array with 40 undefined elements: const points = new Array(40); |
A frequent query arises: How can I determine if a variable is an array?
The challenge lies in the fact that the JavaScript operator typeof yields “object“:
const fruits = [“Banana”, “Orange”, “Apple”]; let type = typeof fruits; |
The reason the typeof operator returns “object” is because a JavaScript array is classified as an object.
To address this issue, ECMAScript 5 (JavaScript 2009) introduced a new method called Array.isArray():
Array.isArray(fruits); |
The instanceof operator yields true if an object is instantiated by a specified constructor:
const fruits = [“Banana”, “Orange”, “Apple”]; fruits instanceof Array; |
Values in objects can be arrays, and values in arrays can be objects.
Example
const myObj = { name: “John”, age: 30, cars: [ {name:“Ford”, models:[“Fiesta”, “Focus”, “Mustang”]}, {name:“BMW”, models:[“320”, “X3”, “X5”]}, {name:“Fiat”, models:[“500”, “Panda”]} ] } |
To access arrays within arrays, use a for-in loop for each nested array:
Example
for (let i in myObj.cars) { x += “<h1>” + myObj.cars[i].name + “</h1>”; for (let j in myObj.cars[i].models) { x += myObj.cars[i].models[j]; } } |