Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    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 }.

  2. 2

    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.

Back

8/9

  1. 1. What Is an Object?
  2. 2. Reading Properties
  3. 3. Changing and Adding Properties
  4. 4. Properties in Square Brackets
  5. 5. Arrays of Objects
  6. 6. Looping Through Arrays of Objects
  7. 7. Objects as Arguments
  8. 8. Functions That Create Objects
  9. 9. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.