Objects as Arguments
Functions and objects go well together. A function can take a whole object as an argument and read the properties it needs:
function describePet(pet) {
return `${pet.name} is ${pet.age} years old.`;
}
const rex = { name: "Rex", species: "dog", age: 3 };
console.log(describePet(rex));
console.log(describePet({ name: "Kiwi", species: "parrot", age: 4 }));Rex is 3 years old.
Kiwi is 4 years old.The parameter pet is a name for whatever object you pass in the call: in the first call it's Rex's object, in the second Kiwi's. Instead of three arguments for the name, species and age, you pass a single one, and the function takes from it what it needs.
A function can also take an array of objects. This one returns the average age of the pets in the array:
function averageAge(pets) {
let total = 0;
for (const pet of pets) {
total += pet.age;
}
return total / pets.length;
}
const pets = [
{ name: "Rex", species: "dog", age: 3 },
{ name: "Bella", species: "cat", age: 2 },
{ name: "Kiwi", species: "parrot", age: 4 }
];
console.log(averageAge(pets));3You write the function once and can use it for any array of pets: for this shop, for another one, or for the pets that arrive tomorrow.
By the way, you have been using an object with functions since the very first lesson. console is an object, and log is one of its properties. Its value is a function, so you call it with parentheses: console.log(). A function stored in an object is called a method. That's also why push() and includes() are called array methods. You can store a function in your own object too:
const dog = {
name: "Rex",
bark: () => console.log("Woof!")
};
dog.bark();Woof!Instructions
Complete the function formatItem: it should return (not print) the name and price of the item it gets, as text like "Ball: 60". The loop at the end then prints all four items: Dog food: 250, Ball: 60 and so on.
Complete the function totalPrice: it should return the sum of the prices of all items in the array items. The last two lines should then be Total: 535 and Small cart: 105.
Start programming for free
7/9