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.
const empty = {};
const book = {
title: "Wings of Fire",
pages: 180,
inLibrary: true,
price: 150 * 2,
};
console.log(book.price); // 30002Nest 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].
const school = {
name: "Green Valley",
address: { city: "Pune", pin: "411001" },
classes: ["6A", "6B", "7A"],
};
console.log(school.address.city, school.classes[0]); // Pune 6A03Add 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".
const player = {
score: 0,
addPoints(n) {
this.score += n;
},
};
player.addPoints(5);
console.log(player.score); // 504Build 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.
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.
const field = "colour";
const choice = { [field]: "teal" };
console.log(choice.colour); // teal06Return 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.
const good = () => ({ ok: true });
const bad = () => { ok: true };
console.log(good(), bad()); // { ok: true } undefinedTry it yourself
- 1
Add a nested object
In the first example, add
address: { city: "Pune" }tostudent. Predict whatconsole.log(student.address.city)prints, then add that line and run. - 2
Break the shorthand
In the second example, rename the variable
scoretopointsbut keepscore,inside the object. Predict the error before you run it. - 3
Compute a key from a loop
In the third example, change
ito5. Predict all three keys, then run and compare.
Code & diagrams
The key `favourite subject` has a space, so it needs quotes when you write it and square brackets when you read it.
Preview
Console
Nothing logged yet.Expected console output
{ name: 'Asha', age: 14, 'favourite subject': 'Maths', isMonitor: true }
Asha 14
object`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
Console
Nothing logged yet.Expected console output
80
Ravi has 80 points
{ name: 'Ravi', score: 80, addPoints: [Function: addPoints], describe: [Function: describe] }Each key in square brackets is an expression, worked out when the object is created.
Preview
Console
Nothing logged yet.Expected console output
{ colour: 'teal', item2: 'pen', size_20: 'large' }
penInteger-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
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.
Break #2
Return an object without parentheses
Write const makeUser = () => { name: "Asha" }; and log makeUser().
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 withnew(they are not constructors), unlikekey: 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...inand spread all follow it. - ▸
A
__proto__: valueentry 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
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: valuepairs separated by commas, like{ name: "Asha", age: 14 }.typeofany object (and any array, andnullby an old mistake) is"object". - 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
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,thisusually means "the object the method was called on", sothis.scorereads that object'sscore. Phase 7.1 explains the full rules forthis; for now, call methods asobj.method(). - 4
ES2015 added three shortcuts. Method shorthand:
greet() { ... }instead ofgreet: 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 keyitem2wheniis 2. - 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 as1, 2, b, a. Don't rely on order for logic; when order matters, use an array. - 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
What is an object in JavaScript, and how is it different from an array?
What do property shorthand, method shorthand and computed keys do? Give an example of each.
Why does () => { ok: true } return undefined?
In what order do an object's keys come back?
Practice
Make an object phone with brand, model, price and a method label() that returns "<brand> <model> costs <price>". Log phone.label().
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.
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: userNameexplicitly 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.