Sub topic 1
Creating Objects with Literals
An object in JavaScript is a collection of properties. Each property pairs a key, which is a name, with a value. The usual way to create an object is the object literal: a pair of curly braces holding key: value pairs separated by commas. This chapter covers the literal syntax, what each literal produces at runtime, and the syntax mistakes people make most often.
Prerequisites
This chapter assumes you already know:
- Basic JavaScript syntax: variables, functions, and control flow
- Primitive types such as strings, numbers, and booleans
- How to create and use arrays
- How to run code in a browser console or Node.js
The Literal Syntax
A property value can be any value: a primitive, an array, a function, or another object.
const book = {
title: "Dune",
pages: 412,
inPrint: true,
author: { name: "Frank Herbert", born: 1920 },
tags: ["sci-fi", "classic"],
};
console.log(typeof book); // "object"
console.log(book.author.name); // "Frank Herbert"Some rules to know:
- A colon separates each key from its value. Using
=instead is a syntax error. - Commas separate the properties. A trailing comma after the last property is allowed, and it keeps diffs clean when you add a property later.
{}creates an empty object. You can add properties to it later.- Keys written without quotes must be valid identifiers. Later chapters cover quoted keys, symbol keys, and computed keys.
Every Evaluation Creates a New Object
A literal works like a recipe: each time JavaScript evaluates it, you get a new, separate object. Two objects with the same contents are still different objects.
function makePoint() {
return { x: 0, y: 0 };
}
const a = makePoint();
const b = makePoint();
console.log(a === b); // false: two distinct objects
console.log({ x: 1 } === { x: 1 }); // false
a.x = 5;
console.log(b.x); // 0: changing a does not affect bThe === operator compares objects by identity, so it does not look at their contents. The chapter on references and copying covers this in more detail.
Other Ways to Create Objects
| Approach | Example | When you see it |
|---|---|---|
| Object literal | `{ a: 1 }` | Almost always; this is the idiomatic choice |
| `Object` constructor | `new Object()` | Older code; gives the same result as `{}` |
| `Object.create` | `Object.create(proto)` | When you need to choose the prototype (covered later) |
| Class or constructor function | `new Point()` | When many objects share one shape and set of methods |
Use a literal unless you have a specific reason to pick one of the others.
Common Errors
Returning a literal from an arrow function
When an arrow function's body starts with {, JavaScript reads the braces as a function body, not as an object.
const wrong = () => { x: 1 }; // block containing a label "x"
const right = () => ({ x: 1 }); // parentheses force an expression
console.log(wrong()); // undefined
console.log(right()); // { x: 1 }A statement that starts with { has the same problem: the parser treats it as a block. Wrapping the literal in parentheses fixes it.
Duplicate keys
If a literal contains the same key twice, the last one wins. JavaScript does not report an error, so a copy-paste mistake can quietly overwrite a value.
const settings = { theme: "dark", size: 12, theme: "light" };
console.log(settings.theme); // "light"Exercise
What does each line log, and why? const f = () => { name: "Ada" }; console.log(f()); console.log({ n: 1 } === { n: 1 });
Show answer
The first line logs undefined. The arrow body's braces form a block, name: is a label, and the function returns nothing. Writing () => ({ name: "Ada" }) would return the object. The second line logs false, because each literal creates a separate object and === compares identity, not contents.
Exercise
Write a literal for a user with the properties id (42), active (true), and address, which is a nested object with city set to "Oslo". Then log the city.
Show answer
const user = { id: 42, active: true, address: { city: "Oslo" } }; console.log(user.address.city); // "Oslo"