Understanding Objects in JavaScript: The "Universal Container"
In our previous guides, we talked about Arrays, which are great for storing lists of items in order. But what if you wanted to describe a specific thing in detail?
Imagine you are building a profile for a student. You could use an array like this: ["John", 21, "Computer Science"]. But looking at that list, how do you know what 21 stands for? Is it his age, his lucky number, or the number of credits he’s taking?
This is where Objects come to the rescue!
What is an Object?
An Object is a collection of related data stored as Key-Value pairs. Instead of using a number (index) to find data, you use a descriptive name (a key).
Think of it like a real-world object—a car. A car isn't just a list; it has specific properties:
Color: Red
Model: Mustang
Year: 1969
Creating an Object
In JavaScript, we use curly braces {} to create an object. Inside, we pair a key with a value using a colon :.
let student = {
name: "John",
age: 21,
course: "Computer Science",
isEnrolled: true
};
Objects vs. Arrays: Which to choose?
Use an Array when the order of items matters (like a top-10 list).
Use an Object when the label of the data matters (like a user profile).
Accessing Properties
There are two main ways to "read" the data inside an object:
1. Dot Notation (The Most Common)
You simply use a period followed by the key name.
console.log(student.name); // Output: John
2. Bracket Notation
You use square brackets and a string. This is useful if your key name has a space in it or is stored in another variable.
console.log(student["course"]); // Output: Computer Science
Updating, Adding, and Deleting
Objects are dynamic. You can change them even after you've created them.
Updating a Value
student.age = 22; // John had a birthday!
Adding a New Property
Just define a new key and give it a value.
student.grade = "A";
Deleting a Property
Use the delete keyword.
delete student.isEnrolled;
Looping Through an Object
Since objects don't have indexes like 0, 1, 2, we use a special loop called a for...in loop to visit every key in the object.
for (let key in student) {
console.log(key + ": " + student[key]);
}
/* Output:
name: John
age: 22
course: Computer Science
grade: A
*/
🛠 Student Assignment
Time to build your own data structure!
The Object: Create an object called
myLaptop.The Properties: Add properties for
brand,processor, andram(e.g., "16GB").The Edit: Update the
ramproperty to a higher value.The Addition: Add a new boolean property called
isTouchscreen.The Final Print: Use a
for...inloop to print every key and value in your object to the console.