Execute Program

Modern JavaScript: Computed Properties

Welcome to the Computed Properties lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • When creating an object, we can write the keys as unquoted words, like Amir in this example:

  • >
    const loginCounts = {Amir: 5};
    loginCounts.Amir;
    Result:
    5Pass Icon
  • We can also create objects with computed keys. To do that, we wrap the key in square brackets, like {[someVariable]: 1}:

  • >
    const name = 'Amir';
    const loginCounts = {[name]: 5};
    loginCounts.Amir;
    Result:
  • The expression inside [square brackets] is evaluated, and its result is used as the property name. In the example above, the name variable contained 'Amir', so that was used as the property name. But computed property names can contain any expression, not just simple variables. For example, we can use string concatenation to build the key dynamically:

  • >
    const loginCounts = {
    ['Be' + 'tty']: 7,
    };
    loginCounts.Betty;
    Result:
    7Pass Icon
  • >
    const betty = {
    name: 'Betty',
    emailConfirmed: true,
    yearJoined: 2015
    };

    function getYearJoined(user) {
    return {[user.name]: user.yearJoined};
    }

    getYearJoined(betty);
    Result:
    {Betty: 2015}Pass Icon
  • Here's a code problem:

    Write a function that takes a user and returns a login count object for this user, mapping their name to their loginCount. Use a computed property to construct the object. Our pre-written code will call your function for multiple users.

    const users = [
    {name: 'Amir', loginCount: 5},
    {name: 'Betty', loginCount: 16},
    ];
    function loginCount(user) {
    return {[user.name]: user.loginCount};
    }
    [
    loginCount(users[0]),
    loginCount(users[1]),
    ];
    Goal:
    [{Amir: 5}, {Betty: 16}]
    Yours:
    [{Amir: 5}, {Betty: 16}]Pass Icon