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'
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
thisthat refers to the parent object. We can access its properties by doingthis.somePropertyName:>
const address = {city: 'Paris',country: 'France',addressString() { return `${this.city}, ${this.country}`; },};address.addressString();Result:
'Paris, France'
Shorthand methods can also call other shorthand methods.
Here's a code problem:
Add a new
volumemethod to this object using JavaScript's shorthand method syntax. (The volume is the base area times the height. We've provided an existingbaseAreamethod 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:
60