Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript new Array()

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(40100152510);
const points = [40100152510];

The use of the new keyword can lead to unexpected outcomes:

// Create an array with three elements:
const points = new Array(401001);
// Create an array with two elements:
const points = new Array(40100);
// 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);  

How to Recognize an Array

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.

Solution 1:

To address this issue, ECMAScript 5 (JavaScript 2009) introduced a new method called Array.isArray():

Array.isArray(fruits);

Solution 2:

The instanceof operator yields true if an object is instantiated by a specified constructor:

const fruits = [“Banana”“Orange”“Apple”];

fruits instanceof Array;

Nested Arrays and Objects

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];
  }
}