array of custom objects javascript

Array of Custom Objects in JavaScript

Working with arrays is a common task in JavaScript programming. You may want to store a collection of objects that have custom properties and methods. This is where arrays of custom objects come into play.

To create an array of custom objects in JavaScript, you first need to define the object's structure using a constructor function. This function will be used to create instances of the object.

Defining a Constructor Function

Here's an example of defining a constructor function for a custom object:


function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
  };
}

This constructor function defines a Person object with two properties (name and age) and one method (greet). The greet method logs a greeting message to the console.

Creating Instances of the Object

To create instances of the Person object, you can use the new keyword:


var person1 = new Person("Alice", 25);
var person2 = new Person("Bob", 30);

This code creates two instances of the Person object with different values for the name and age properties.

Storing Instances in an Array

Now that you have instances of the Person object, you can store them in an array:


var people = [person1, person2];

This code creates an array called people with two elements, each of which is an instance of the Person object.

Accessing Elements in the Array

You can access individual elements in the people array using array indexing:


console.log(people[0].name); // Output: "Alice"
console.log(people[1].age); // Output: 30

This code logs the values of the name and age properties of the first and second elements in the people array, respectively.

Alternative Approach

Another way to create an array of custom objects in JavaScript is to use object literals:


var people = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 }
];

This code creates an array of objects with the same structure as the Person object defined earlier. However, this approach does not allow you to define custom methods for the objects.

Conclusion

Creating an array of custom objects in JavaScript involves defining a constructor function, creating instances of the object, and storing them in an array. You can then access individual elements in the array and their properties. Alternatively, you can use object literals to create an array of objects with the same structure.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe