55 Mins intermediate
9. Objects
Data Structures
Objects
While arrays are ordered lists, Objects store data in Key-Value pairs. They are the cornerstone of representing real-world entities in code.
๐ Object Creation & Access
const player = {
username: "GhostUser",
level: 42,
isOnline: true
};
// Dot notation (Standard)
console.log(player.username);
// Bracket notation (Used when the key is dynamic)
const keyToFind = "level";
console.log(player[keyToFind]);
OutputGhostUser
42
42
โ๏ธ Modifying Objects
const server = { name: "Main DB", status: "Active" };
// Updating a value
server.status = "Maintenance";
// Adding a new key-value pair
server.ip = "192.168.1.1";
console.log(server);
Output{ name: 'Main DB', status: 'Maintenance', ip: '192.168.1.1' }
๐๏ธ Nested Objects & Methods
Objects can contain other objects, and they can even contain functions (which are called "Methods").
const company = {
name: "VoidX",
ceo: {
name: "Prince",
city: "Tarkwa"
},
greet: function() {
return "Welcome to " + this.name;
}
};
console.log(company.ceo.city);
console.log(company.greet());
OutputTarkwa
Welcome to VoidX
Welcome to VoidX
Knowledge Check
Ready to test your understanding of 9. Objects?