Objects

Objects have received some new updates in this edition of the language, including everything from new methods to updated syntax.

Shorthand methods

One nice addition to objects is the shorthand method syntax. We will see this pattern come up again when we talk about classes. As a reminder, here is what the original syntax looks like.

Press + to interact
let flower = {
height: 10,
colour: 'yellow',
grow: function() {
this.height += 5;
}
}

Here we have a simple flower object which has a height and colour and a grow method. When defining a method we provide a function as a value to the property on an object. In this case we use an anonymous function. We could, if we wanted, also provide a named function.

Press + to interact
let flower = {
height: 10,
colour: 'yellow',
grow: function growMethod() {
this.height += 5;
}
}

The benefit of providing a named function is that we could use this name inside of our method if we need to call it recursively. With the new shorthand method syntax, we can exclude the anonymous function all together.

Press + to interact
let flower = {
height: 10,
colour: 'yellow',
grow() {
this.height += 5;
}
}

Look at that! I think this looks really nice. ...

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy