Command Palette

Search for a command to run...

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

Key order and duplicate keys

Integer-like keys come first in number order. "-1" isn't a valid array index, so it counts as an ordinary string key. The duplicate size keeps its first position but takes the last value.

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?

Key order and duplicate keys

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

[ '1', '2', 'b', 'a', '-1' ]
{ size: 'large', colour: 'red' }