Arrays are brilliant for lists of similar things: a list of names, a list of scores, a list of foods. But what if you want to describe one thing that has lots of different details?
Let's say you want to store information about a student. You could try an array:
const student = ["Omar", 17, true, "omelet"];
But... what does 17 mean? Is that his age? His shoe size? The number of times he's been late this term? And is true saying he's a student, or that he likes cats, or that he's secretly a robot? You'd have to remember what every position means, and so would everyone else who reads your code. That's a recipe for bugs.
What we really want is to label each piece of information. That's exactly what an object does:
const student = {
name: "Omar",
age: 17,
isStudent: true,
favFood: "omelet",
};
console.log(student);
It prints
{ name: 'Omar', age: 17, isStudent: true, favFood: 'omelet' }Now everything is crystal clear. The 17 is his age. The true means isStudent. No guessing!
An object is like an ID card. It describes one person (or thing), and each detail has a label: Name: Omar. Age: 17. Student: Yes. Favorite food: omelet. The label is called the key, and the detail is called the value. Together, each key and value is called a property.
Objects are everywhere in JavaScript. A user on a website is an object. A product in a shop is an object. A message in a chat app, a song in a playlist, a character in a game: all objects. They might just be the most important data structure in the whole language.