Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.1 — Object Literals
JavaScript · Example 2 of 4 ES2015+

Methods and shorthand

name and score use property shorthand; addPoints uses method shorthand; describe is the older long form. Both methods get a name, which is why the console shows [Function: describe].

An object is a collection of named values called properties; you write one with curly braces, and its values can be anything, including functions (methods), with shorthand and computed keys to keep the code short.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make an object phone with brand, model, price and a method label() that returns "<brand> <model> costs <price>". Log phone.label().

02

Given const key = "level" and const value = 3, build an object whose key is the value of key, using a computed key, and log it.

03

Write an arrow function point(x, y) that returns { x, y } using property shorthand. Log point(2, 5).

Explain it without notes

01

What is an object in JavaScript, and how is it different from an array?

02

What do property shorthand, method shorthand and computed keys do? Give an example of each.

03

Why does () => { ok: true } return undefined?

04

In what order do an object's keys come back?

Methods and shorthand ES2015+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

80
Ravi has 80 points
{ name: 'Ravi', score: 80, addPoints: [Function: addPoints], describe: [Function: describe] }