Command Palette

Search for a command to run...

Hectal
PHASE 6Beginner ~26 min· topic 1 of 7

Topic 6.1

Object Literals

In one line

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.

Think of it like this

A school ID card. It has labels printed on it (Name, Class, Roll number, Blood group) and next to each label a value (Asha, 8B, 21, O+). You find a value by its label, not by its position. A JavaScript object is exactly that card: a set of labels, each with a value.

Words you'll meet

New words in this topic, in plain English. Come back here whenever one feels fuzzy.

Object
A value that groups other values under names, like an ID card with labels and values.
Property
One name-value pair inside an object, like age: 14.
Key
The name part of a property. It is always a string (or a symbol).
Object literal
Writing an object directly in code with curly braces: { name: "Asha" }.
Method
A function stored as a property of an object, called with obj.method().
Nested object
An object stored as the value of another object's property.
Shorthand property
{ name } as a short way to write { name: name }.
Computed key
A key written in square brackets, { [expr]: value }, worked out when the object is made.

Step by step

01Make an empty object, then a full one

{} is an empty object. Put properties inside, one key: value per line, separated by commas. The value can be any expression; it is worked out once, when the object is made.

app.jswhole filejavascript
const empty = {};
const book = {
  title: "Wings of Fire",
  pages: 180,
  inLibrary: true,
  price: 150 * 2,
};
console.log(book.price); // 300

02Nest objects and arrays

A value can be another object or an array, so one object can describe something complex. Read deep values by chaining: school.address.city, school.classes[0].

app.jswhole filejavascript
const school = {
  name: "Green Valley",
  address: { city: "Pune", pin: "411001" },
  classes: ["6A", "6B", "7A"],
};
console.log(school.address.city, school.classes[0]); // Pune 6A
Nest objects and arraysdiagram
Rendering diagram…

03Add behaviour with a method

Store a function as a property and the object can do things. With method shorthand you drop : function. this.score means "the score of the object I was called on".

app.jswhole filejavascript
const player = {
  score: 0,
  addPoints(n) {
    this.score += n;
  },
};
player.addPoints(5);
console.log(player.score); // 5

04Build objects from variables

When variables already have the right names, property shorthand saves typing. This is how most code packs values together before returning or sending them.

app.jswhole filejavascript
const name = "Ravi";
const age = 13;
const person = { name, age }; // same as { name: name, age: age }
console.log(person); // { name: 'Ravi', age: 13 }

05Let JavaScript choose the key

Square brackets around a key mean "work this out first". Use it when the key comes from a variable, user input or a calculation.

app.jswhole filejavascript
const field = "colour";
const choice = { [field]: "teal" };
console.log(choice.colour); // teal

06Return an object from an arrow function

Wrap the literal in parentheses. Without them, the engine reads { as the start of the function body, finds a label called ok, and the function returns undefined.

app.jswhole filejavascript
const good = () => ({ ok: true });
const bad = () => { ok: true };
console.log(good(), bad()); // { ok: true } undefined

Try it yourself

  1. 1

    Add a nested object

    In the first example, add address: { city: "Pune" } to student. Predict what console.log(student.address.city) prints, then add that line and run.

  2. 2

    Break the shorthand

    In the second example, rename the variable score to points but keep score, inside the object. Predict the error before you run it.

  3. 3

    Compute a key from a loop

    In the third example, change i to 5. Predict all three keys, then run and compare.

Code & diagrams

An object as an ID card New tab

The key `favourite subject` has a space, so it needs quotes when you write it and square brackets when you read it.

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

{ name: 'Asha', age: 14, 'favourite subject': 'Maths', isMonitor: true }
Asha 14
object
Methods and shorthand ES2015+ New tab

`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]`.

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] }
Computed keys ES2015+ New tab

Each key in square brackets is an expression, worked out when the object is created.

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

{ colour: 'teal', item2: 'pen', size_20: 'large' }
pen
Key order and duplicate keys New tab

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.

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

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

Break it on purpose

Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.

Break #1

Forget the comma

In the first example, delete the comma after age: 14.

terminal
$ Console
── what you'll see ──
Uncaught SyntaxError: Unexpected string

Break #2

Return an object without parentheses

Write const makeUser = () => { name: "Asha" }; and log makeUser().

terminal
$ Console
── what you'll see ──
undefined

Myth vs fact

Myth

Object keys can be numbers.

Fact

Every key is a string or a symbol. { 1: "a" } stores the key "1", which is why obj[1] and obj["1"] read the same property.

Myth

Objects have no order, so the keys come out randomly.

Fact

The order is defined by the standard: integer-like keys in rising order, then string keys in the order they were added, then symbols. It's predictable, but it isn't the order you wrote if you mix in integer keys.

Myth

const makes an object unchangeable.

Fact

const only stops the variable from pointing at a different object. You can still add, change and delete properties. To lock the object itself, see Object.freeze in Topic 6.5.

Pro corner

Extra depth for experienced readers. New to this? Skip it for now and come back later.

  • ▸

    Engines like V8 give objects a hidden shape (V8 calls it a map or hidden class) based on which keys were added and in what order. Objects created the same way share a shape, which makes property reads fast. Creating objects with the same keys in the same order, and not deleting properties, keeps code on the fast path.

  • ▸

    Method shorthand is not only shorter: shorthand methods can use super (Phase 7.7) and cannot be used with new (they are not constructors), unlike key: function () {}.

  • ▸

    Property order is set by the spec's OrdinaryOwnPropertyKeys: array-index keys (integers from 0 to 2^32 - 2) ascending, then other strings in creation order, then symbols in creation order. Object.keys, JSON.stringify, for...in and spread all follow it.

  • ▸

    A __proto__: value entry in a literal doesn't create a property: it sets the object's prototype (Phase 7.3). A computed ["__proto__"] key or shorthand __proto__ creates a normal property instead. This edge case matters when building objects from untrusted keys.

Remember this

  1. 1

    An object is a value that groups other values under names. Each name-value pair is a property. The name is the key and the thing stored is the value. The simplest way to make one is an object literal: curly braces with key: value pairs separated by commas, like { name: "Asha", age: 14 }. typeof any object (and any array, and null by an old mistake) is "object".

  2. 2

    Keys are strings (or symbols, which Phase 14 covers). When a key is a valid name (letters, digits, _ or $, not starting with a digit) you can leave the quotes off: { age: 14 }. Any other key needs quotes: { "favourite subject": "Maths", "2nd-place": "Ravi" }. Number keys are turned into strings: { 1: "one" } has the key "1". If you write the same key twice, the last one wins.

  3. 3

    Values can be anything: numbers, strings, booleans, null, arrays, other objects (a nested object), and functions. A function stored in a property is called a method. Inside a method, this usually means "the object the method was called on", so this.score reads that object's score. Phase 7.1 explains the full rules for this; for now, call methods as obj.method().

  4. 4

    ES2015 added three shortcuts. Method shorthand: greet() { ... } instead of greet: function () { ... }. Property shorthand: { name, age } means { name: name, age: age }, taking the values from variables with the same names. Computed keys: { [expression]: value } works out the key when the object is made, for example { ["item" + i]: "pen" } gives the key item2 when i is 2.

  5. 5

    Properties come back in a fixed order. Integer-like keys ("0", "1", "42") come first, in rising number order; then all other string keys in the order they were added. So { b: 1, 2: "x", a: 2, 1: "y" } lists its keys as 1, 2, b, a. Don't rely on order for logic; when order matters, use an array.

  6. 6

    Two syntax traps. A trailing comma after the last property is allowed and recommended: adding a property later changes one line instead of two. And a { at the very start of a statement is read as a block, not an object: an arrow function that returns an object must wrap it in parentheses, () => ({ ok: true }), or the braces become the function body.

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?

Practice

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).

Trade-offs

  • ↔

    Objects are ideal for a fixed set of named fields. For a collection where keys are added and removed all the time, or keys aren't strings, a Map (Phase 14.3) is faster for frequent changes and keeps any key type.

  • ↔

    Shorthand makes code shorter but hides where each value came from; in long functions, writing name: userName explicitly can be clearer than renaming variables to fit shorthand.

Done when you can

  • I can write an object literal with strings, numbers, arrays, nested objects and methods.

  • I know when a key needs quotes and that number keys become strings.

  • I can use property shorthand, method shorthand and computed keys.

  • I can predict the order of an object's keys.

  • I wrap object literals in parentheses when an arrow function returns them.