Arrays and Objects
Lesson Progress0%
Object Methods & Iteration
Topic Overview
Take your time to understand each concept. Practice with the examples below!
Objects can do more than just store data - they can also contain functions (called methods) and we can loop through their properties!
Object Methods (functions inside objects):
const calculator = { name: "Super Calc", add: function(a, b) { return a + b; }, multiply: function(a, b) { return a * b; }};// Using methods:calculator.add(5, 3); // 8calculator.multiply(4, 7); // 28
Modern method syntax (ES6):
const dog = { name: "Buddy", age: 3, bark() { // Shorter syntax! return "Woof! My name is " + this.name; }};
Iterating through objects:
- •Object.keys() - Get all property names
const keys = Object.keys(person); // ["name", "age", "city"]
- •Object.values() - Get all values
const values = Object.values(person); // ["Alice", 25, "Boston"]
- •Object.entries() - Get key-value pairs
const entries = Object.entries(person); // [["name", "Alice"], ["age", 25], ["city", "Boston"]]
- •for...in loop - Loop through properties
for (let key in person) { console.log(key + ": " + person[key]);}
Real example - user profile:
const user = { username: "coder123", score: 150, level: 5, levelUp() { this.level++; this.score += 50; }};
Ready to practice? Try the exercise below to reinforce your learning!
Try it yourself
Create an object with methods and iterate through its properties using Object.keys().
Loading...