Objects
While arrays use positional indexes (0, 1, 2) to identify data, Objects use named Keys. Think of objects as detailed dictionaries!
Creating Objects
You define objects using curly braces {} and create properties as key: value pairs.
const user = {
firstName: "John",
lastName: "Doe",
age: 30,
isAdmin: true,
hobbies: ["Reading", "Gaming"]
};
Accessing Object Properties
There are two primary ways to retrieve data from an object:
1. Dot Notation (Preferred)
console.log(user.firstName); // John
console.log(user.age); // 30
2. Bracket Notation
Required when the key name has spaces, special characters, or when you are accessing a key dynamically via a variable.
const variableKey = "lastName";
console.log(user[variableKey]); // Doe
// console.log(user.variableKey); // undefined (Looks for literal key 'variableKey')
Modifying Objects
Unlike primitives, objects defined with const can be mutated! const merely prevents re-assigning the memory pointer to a completely new object.
const car = { make: "Honda", year: 2020 };
// Valid! (Modifying internals)
car.year = 2022;
car.color = "Blue"; // Adds a new property dynamically!
console.log(car); // { make: 'Honda', year: 2022, color: 'Blue' }
// Invalid! (Re-assignment)
// car = { make: "Toyota" }; // TypeError: Assignment to constant variable.