Functions That Create Objects
A function can also return an object. This is handy when you create many objects of the same shape: you write the keys only once, in the function, and every object it creates has the same properties.
function createBook(title, author) {
return {
title: title,
author: author,
available: true
};
}
const book = createBook("Matilda", "Roald Dahl");
console.log(book);{ title: "Matilda", author: "Roald Dahl", available: true }title: title may look strange. On the left of the colon is the key, the name of the new property. On the right is its value: the parameter title, which holds "Matilda" in this call. A new book is always available, so available is true in every book the function creates.
In other people's code you'll often see a shorter form: { title, author }. When a property should have the same name as the variable that holds its value, you can write the name just once. { title, author } means exactly the same as { title: title, author: author }. You can use either.
A new object can go straight into an array:
const library = [];
library.push(createBook("Matilda", "Roald Dahl"));
library.push(createBook("Momo", "Michael Ende"));
console.log(library);[{ title: "Matilda", author: "Roald Dahl", available: true }, { title: "Momo", author: "Michael Ende", available: true }]A typical mistake is to forget return. The function then returns undefined, and the library would be [undefined, undefined].
Instructions
Complete the function createProduct so that it returns an object with the properties name and price. The program should then print { name: "Bird seed", price: 90 }.
Below, create a constant cart with an empty array. Use push() and createProduct() to add two products to it: "Cat bed" for 400 and "Cat toy" for 35. Print cart.
Start programming for free
8/9