How to make an array of JavaScript objects

Learn how to create a JavaScript array of objects with an example, from constructing the array to manipulating its elements.

Creating an Array of JavaScript Objects

Creating an array of JavaScript objects is easy. An array is a special type of JavaScript object that stores a collection of values. Each value is an object, and can contain any type of data, such as numbers, strings, functions, and more.

To create an array of JavaScript objects, you simply use the new keyword and the Array constructor. For example, the following code creates an array of five objects:

let arrayOfObjects = new Array(
  { name: 'John', age: 30 },
  { name: 'Paul', age: 28 },
  { name: 'George', age: 27 },
  { name: 'Ringo', age: 26 },
  { name: 'Pete', age: 25 }
);

The above code creates an array with five objects, each with two properties: name and age. Note that the array is enclosed in square brackets [] and separated by commas ,.

You can access the objects in the array using their index number. For example, to access the third object in the array, you would use the following code:

let thirdObject = arrayOfObjects[2];

The above code assigns the third object in the array to the thirdObject variable. You can then access the properties of the object, such as its name and age, like so:

let thirdObjectName = thirdObject.name; // 'George'
let thirdObjectAge = thirdObject.age; // 27

In summary, creating an array of JavaScript objects is easy. You simply use the new keyword and the Array constructor, and then you can access the objects in the array using their index number.

Answers (0)