🌱BeginnerCollections
Objects
Creating and working with key-value pairs JavaScript's fundamental data structure.
Overview
Objects are collections of key-value pairs. In JavaScript, almost everything is an object or can behave like one arrays, functions, dates, and even regular expressions are objects under the hood. Objects are the primary way to group related data and behavior.
You create an object with the literal syntax: {}. Keys (also called property names) are strings (or Symbols), and values can be anything: strings, numbers, booleans, other objects, arrays, or functions. When a function is stored as a property, it is called a method.
You access properties with dot notation (obj.key) or bracket notation (obj["key"]). Bracket notation is necessary when the key is dynamic (stored in a variable) or contains special characters.
Key Points
- •Object literal syntax: const obj = { key: value, anotherKey: value }
- •Dot notation: obj.key clean but only works with valid identifiers
- •Bracket notation: obj["key"] works with any string, including dynamic keys
- •You can add, update, and delete properties after an object is created
- •Object.keys(obj), Object.values(obj), Object.entries(obj) iterate an object's properties
- •Shorthand property: if variable name matches key name, const obj = { x, y } means { x: x, y: y }
Examples
Creating objects, accessing and modifying properties
const person = {
name: "Alice",
age: 30,
city: "London",
};
console.log(person.name); // "Alice"
console.log(person["age"]); // 30
person.age = 31; // update
person.job = "Engineer"; // add new property
delete person.city; // remove property
console.log(person);Iterating with Object.keys, Object.values, Object.entries
const config = { host: "localhost", port: 5432, ssl: false };
console.log(Object.keys(config));
// ["host", "port", "ssl"]
console.log(Object.values(config));
// ["localhost", 5432, false]
for (const [key, value] of Object.entries(config)) {
console.log(`${key}: ${value}`);
}Methods and shorthand property syntax
const name = "Bob";
const age = 25;
// Shorthand: { name, age } === { name: name, age: age }
const user = {
name,
age,
greet() {
return `Hi, I'm ${this.name}`;
},
};
console.log(user.greet()); // Hi, I'm BobCommon Mistakes
- Using dot notation with a dynamic key obj.key is always the literal string "key", not the variable
- Forgetting that Object.keys/values return arrays, not objects you can iterate them
- Comparing objects with === checks identity (same reference), not equality of contents
Exercises
Write JavaScript code to solve each exercise. Run it and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4