Objects

Computer Science · JavaScript

Question 1 of 10

0

    What does this JavaScript code log? const o = { a: 9, b: 7 }; o.a = o.b + 20; console.log(o.a);

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Objects explained

    An object groups related values under named properties, written as key-value pairs. Objects model things such as a book or a user, and their properties can be read, changed, added and removed while the program runs.

    Properties are read with dot notation, such as book.title, or with bracket notation, such as book["title"], which is needed when the key is stored in a variable. Assigning to a new key adds a property, and the delete operator removes one. Shorthand syntax creates properties from variables with the same names.

    const book = { title: "Dune", pages: 412 };
    book.pages = book.pages + 8;
    const copy = book;
    copy.title = "Dune Messiah";
    console.log(book.title, book.pages, Object.keys(book).length);
    

    Caveat: objects are stored by reference. A variable holds a pointer to the object, so copy = book gives access to the same object, and changes made through either name are visible through the other. Use a spread copy when an independent shallow copy is needed.

    Worked example

    pages becomes 412 + 8 = 420. Because copy and book point to the same object, setting copy.title also changes book.title. Object.keys(book) returns two names, title and pages. The program prints Dune Messiah, 420 and 2.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this JavaScript code log?

      const o = { a: 7, b: 11 }; o.a = o.b + 19; console.log(o.a);

    • Medium

      What does this JavaScript code log?

      const p = { n: 10 }; const q = p; const r = { ...p }; q.n += 11; r.n += 20; console.log(r.n);

    • Hard

      What does this JavaScript code log?

      const o = {}; o["2"] = 2; o[true] = 5; delete o["2"]; o[2] = 4; console.log(Object.keys(o).length);