How to Create a List of Objects in JavaScript
This article will demonstrate creating a list of objects in JavaScript and their properties and methods.
Create a List of Objects in JavaScript
JavaScript is an object-oriented programming language, and everything is considered an object in any object-oriented programming language.
An object is a real-world entity having state & behavior - for example, a car. A car has state (color) and behavior (speed, acceleration, etc.).
Typically, an object is accompanied by a class in other programming languages, and class defines an object’s blueprints. But JavaScript does not require a class for objects creation since it is purely template-based.
Syntax:
const object = {
// object's different member's names & values
name1: value1,
name2: value2,
name3: value3
};
Let’s see a simple demonstration in JavaScript.
const employee = {
id: 541,
company: ['Delft', 'Stack'],
details: function() {
document.write(
'I work for ${this.name[0]} ${this.name[1]} with employee id ${this.id}');
// I work for DelftStack with employee id 541
}
};
The first two members of the above employee object are data items, and we usually call them object’s properties/states. The third item is a function that allows the object to do something with the data, and we typically call it the object’s methods/behavior.
Object Properties in JavaScript
In simple words, an object is a collection of properties. Data items or values in a JavaScript object are called its properties.
Apart from read-only properties, we can add, update and delete properties.
In the following code, we explain different methods for accessing object properties.
var student = {
rollNo: 'BSE541',
name: 'Joe Burns',
age: 23,
degree: 'Computer Science',
};
student.age; // accessing object using object.property
student[age]; // accessing object using object[property]
x = 'age';
student[x]; // using variable to access object's property
Object Methods in JavaScript
In simple words, the actions that JavaScript objects can perform are called methods.
var student = {
rollNo: 'BSE541',
name: 'Joe Burns',
age: 23,
degree: 'Computer Science',
};
document.getElementById('demo').innerHTML = 'Hi ' + student.name;
// print "Hi Joe Burns"
Below is the complete HTML example demonstrating JavaScript object properties and methods.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects Example</h2>
<p id="object"> </p>
<script>
const company = {
name:"DelftStack",
id:571,
location:"USA"
};
document.getElementById("object").innerHTML = company.name + " is a technology company registered in the " + company.location + " with id: " + company.id;
</script>
</body>
</html>
Output:
JavaScript Objects Example
DelftStack is a technology company registered in the USA with id: 571