Execute Program

Modern JavaScript: Shorthand Properties

Welcome to the Shorthand Properties lesson!

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

  • Object keys often refer to variables with the same name. Historically, we'd often have to use the pattern below.

  • >
    const name = 'Amir';
    const user = {
    name: name
    };
    user.name;
    Result:
    'Amir'Pass Icon
  • This works, but it can cause a lot of code bloat once we add more properties.

  • >
    const name = 'Amir';
    const catName = 'Ms. Fluff';
    const city = 'Paris';
    const age = 36;

    const user = {
    name: name,
    catName: catName,
    city: city,
    age: age,
    };
    [user.name, user.age];
    Result:
    ['Amir', 36]Pass Icon
  • In modern JavaScript, we can shorten this significantly. When the object's key refers to a variable of the same name, we only have to specify that name once. Instead of {name: name}, we can just write {name}.

  • >
    const name = 'Amir';
    const catName = 'Ms. Fluff';
    const city = 'Paris';
    const age = 36;

    const user = {name, catName, city, age};
    [user.name, user.age];
    Result:
    ['Amir', 36]Pass Icon
  • We can't use this to refer to a variable that doesn't exist. As with the older syntax, that will cause an error. (You can type error when a code example will throw an error.)

  • >
    const user = {age};
    Result:
    ReferenceError: age is not definedPass Icon