Sub topic 1
Creating Objects with Literals
An object in JavaScript is a collection of properties. Each property pairs a key with a value. The most common way to create an object is the object literal: a pair of curly braces with zero or more key: value entries inside. This chapter covers how a literal is written and evaluated, which values it can hold, the syntax errors people hit most often, and how literals compare with the other ways of creating objects.
Prerequisites
This chapter assumes you already know:
- Basic JavaScript syntax: variables (
const,let), functions, and control flow - Primitive types such as strings, numbers, and booleans
- Arrays and how to iterate over them
- How to run JavaScript in a browser console or with Node.js
Reading and writing properties gets only light use here. Dot and bracket notation have their own chapter next.
The Shape of an Object Literal
An object literal is an expression. It produces a new object each time it is evaluated. Inside the braces, entries are separated by commas, and each entry is a key, a colon, and a value.
const empty = {};
const book = {
title: "Dune",
author: "Frank Herbert",
pages: 412,
inPrint: true,
};
console.log(book.title); // "Dune"
console.log(empty); // {}A few rules apply:
- The key comes before the colon. If the key is a valid identifier (letters, digits,
$,_, and not starting with a digit), you can write it without quotes. - The value comes after the colon and can be any JavaScript expression.
- Commas separate entries. A trailing comma after the last entry is allowed and is common style, because adding a line later then changes only one line in a diff.
Keys that need quotes
Keys that are not valid identifiers must be written as string literals:
const headers = {
"Content-Type": "application/json",
"x-request-id": "abc123",
"first name": "Ada",
};
console.log(headers["Content-Type"]); // "application/json"Reserved words such as class, default, and new are allowed as unquoted keys. { class: "A", new: true } is valid.
Numeric keys become strings
You can write a number as a key, but the property key is stored as a string. The number is first converted to its canonical string form.
const codes = { 1: "one", 1.5: "one and a half", 0x10: "sixteen" };
console.log(Object.keys(codes)); // ["1", "16", "1.5"]
console.log(codes["16"]); // "sixteen"The hex literal 0x10 became the key "16". The order also changed, because integer-like keys are listed first. The chapter on listing properties explains that order rule.
Values Can Be Any Expression
The value side of each entry is evaluated, and the result is stored. That means values can be computed, nested, or functions.
const price = 12.5;
const quantity = 4;
const order = {
id: "A-1001",
total: price * quantity,
items: ["pen", "notebook"],
shipping: {
method: "ground",
address: { city: "Lisbon", zip: "1100-148" },
},
createdAt: new Date(2026, 0, 15),
describe: function () {
return "Order " + this.id + " totals " + this.total;
},
};
console.log(order.total); // 50
console.log(order.shipping.address.city); // "Lisbon"
console.log(order.items.length); // 2
console.log(order.describe()); // "Order A-1001 totals 50"Values are evaluated from left to right, in the order they appear in the source. This matters when the value expressions have side effects:
let n = 0;
const seq = { first: ++n, second: ++n, third: ++n };
console.log(seq); // { first: 1, second: 2, third: 3 }A value expression cannot refer to the object being built. While the literal is being evaluated, the object has not been assigned to any variable yet:
const box = {
width: 10,
// height: box.width * 2, // ReferenceError: Cannot access 'box' before initialization
};To derive one property from another, compute the shared value first and store it in a variable, or use a getter. Getters are covered in a later chapter.
Every Evaluation Creates a New Object
Two literals with the same contents are two different objects. Comparison with === checks identity, not contents.
console.log({} === {}); // false
console.log({ a: 1 } === { a: 1 }); // false
function makePoint(x, y) {
return { x: x, y: y };
}
const p1 = makePoint(1, 2);
const p2 = makePoint(1, 2);
console.log(p1 === p2); // false
console.log(p1 === p1); // trueThis is why a function that returns a literal works as a simple factory. Each call gets its own object, and changes to one don't affect the others. What a variable actually holds when it "contains" an object is covered in the chapter on references and copying.
Duplicate Keys
If a literal repeats a key, the last value wins. The property keeps the position where the key first appeared.
const settings = { mode: "light", size: 2, mode: "dark" };
console.log(settings); // { mode: "dark", size: 2 }Duplicates are legal even in strict mode, but they are almost always a mistake. ESLint's no-dupe-keys rule reports them. One intentional use of this behavior is applying overrides after defaults, which usually happens through spread syntax rather than repeated literal keys.
Common Errors
| Mistake | Example | What happens | Fix |
|---|---|---|---|
| `=` instead of `:` | `{ name = "Ada" }` | SyntaxError (outside destructuring) | `{ name: "Ada" }` |
| Missing comma | `{ a: 1 b: 2 }` | SyntaxError: unexpected identifier | `{ a: 1, b: 2 }` |
| Semicolons between entries | `{ a: 1; b: 2 }` | SyntaxError | Use commas |
| Unquoted key with a hyphen | `{ first-name: "Ada" }` | SyntaxError | `{ "first-name": "Ada" }` |
| Returning a literal from an arrow function body | `() => { ok: true }` | Returns `undefined` | `() => ({ ok: true })` |
| Statement starting with `{` | `{ a: 1, b: 2 };` | SyntaxError | Assign it or wrap it in parentheses |
The block versus object ambiguity
The last two rows share a cause. When { appears where a statement is expected, JavaScript parses it as a block, not an object literal. Inside a block, ok: true is a label named ok followed by the expression true. The parse succeeds, and nothing is returned.
const wrong = () => { ok: true };
const right = () => ({ ok: true });
console.log(wrong()); // undefined
console.log(right()); // { ok: true }The parentheses force expression context, so the braces become an object literal.
Object Literals Are Not JSON
JSON syntax was taken from JavaScript object literals, but it is stricter, and the two are often confused.
| Feature | Object literal | JSON |
|---|---|---|
| Unquoted keys | Allowed | Not allowed; keys must be double-quoted |
| Single-quoted strings | Allowed | Not allowed |
| Trailing commas | Allowed | Not allowed |
| Functions, `undefined`, `Date` objects as values | Allowed | Not representable |
| Comments | Allowed | Not allowed |
| What it is | Code that creates an object | Text that must be parsed |
const text = '{"title": "Dune", "pages": 412}';
const parsed = JSON.parse(text);
console.log(parsed.pages); // 412
// JSON.parse("{ title: 'Dune' }"); // SyntaxError: keys and strings not in JSON formOther Ways to Create Objects
Literals cover most everyday needs. You will also see these alternatives:
// 1. The Object constructor: same result as {}, but longer
const a = new Object();
a.kind = "constructor";
// 2. Object.create: choose the new object's prototype
const base = { greet() { return "hi from " + this.name; } };
const b = Object.create(base);
b.name = "b";
// 3. A class: a reusable blueprint
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const c = new Point(3, 4);
// 4. Object.fromEntries: build from key-value pairs
const d = Object.fromEntries([["red", "#f00"], ["green", "#0f0"]]);
console.log(a.kind); // "constructor"
console.log(b.greet()); // "hi from b"
console.log(c.x, c.y); // 3 4
console.log(d.green); // "#0f0"Use a literal when you need a single object with a known shape, such as configuration, a function's return value, or a record of data. Use Object.fromEntries when the keys are only known at run time. Reach for classes when many objects share behavior. Object.create gets its full explanation in the prototype chapter.
Summary
- An object literal
{ key: value, ... }is an expression that creates a new object every time it runs. - Keys that are not valid identifiers need quotes. Numeric keys are converted to strings.
- Values can be any expression and are evaluated left to right. They cannot refer to the object being built.
- With duplicate keys, the last value wins and the key keeps its first position.
- A
{in statement position starts a block. Wrap the literal in parentheses when returning it from a concise arrow function. - JSON is a stricter text format and is not the same thing as literal syntax.
Exercise
What does this code log, and why? const make = () => { id: 1 }; console.log(make()); Rewrite it so it logs { id: 1 }.
Show answer
It logs undefined. The braces after => are parsed as a function body block, id: is a label, and the function has no return statement. Wrapping the literal in parentheses makes it an expression: const make = () => ({ id: 1 });.
Exercise
Predict the output of console.log(Object.keys({ b: 1, 2: "x", b: 3, 0x1: "y" })) and the value of the b property.
Show answer
The keys are ["1", "2", "b"]. 0x1 becomes the string "1", integer-like keys are listed first in ascending order, and the duplicate b keeps its first position. The value of b is 3 because the last duplicate wins.
Exercise
A teammate writes const rect = { w: 4, h: 3, area: rect.w * rect.h };. What goes wrong, and how would you fix it without a getter?
Show answer
It throws a ReferenceError because rect is not initialized while the literal is being evaluated. Compute the values first: const w = 4, h = 3; const rect = { w: w, h: h, area: w * h };.