Execute Program

Modern JavaScript: Shorthand Methods

Welcome to the Shorthand Methods lesson!

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

  • Modern JavaScript allows us to define methods right inside an object literal.

  • >
    const user = {
    name() { return 'Amir'; }
    };
    user.name();
    Result:
    'Amir'Pass Icon
  • Methods defined in this way are called "shorthand methods".

  • (We've already seen "shorthand properties", which let us say {name}. The similarity of these features' names doesn't indicate a deep relationship. They're only related in that they're both shorthands.)

  • Shorthand methods have a this that refers to the parent object. We can access its properties by doing this.somePropertyName:

  • >
    const address = {
    city: 'Paris',
    country: 'France',
    addressString() { return `${this.city}, ${this.country}`; },
    };
    address.addressString();
    Result:
    'Paris, France'Pass Icon
  • Shorthand methods can also call other shorthand methods.

  • Here's a code problem:

    Add a new volume method to this object using JavaScript's shorthand method syntax. (The volume is the base area times the height. We've provided an existing baseArea method for you to call.)

    const rectangle3D = {
    width: 3,
    depth: 4,
    height: 5,
    baseArea() { return this.width * this.depth; },
    volume() { return this.baseArea() * this.height; },
    };
    rectangle3D.volume();
    Goal:
    60
    Yours:
    60Pass Icon