Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 156 ยท Objects

Objects

Create JavaScript objects with literals, read and change properties with dot and bracket notation, write methods, and use shorthand and computed keys.

An object is a collection of named values. Each value is stored under a key (also called a property name), and together a key and its value form a property. Objects let you keep related data together โ€” a user's name, email and settings; a product's title, price and stock โ€” and pass it around as one thing.

Objects are everywhere in JavaScript. Arrays, functions, dates, DOM elements and errors are all objects under the hood. This lesson covers the everyday essentials: object literals, reading and writing properties, the two ways of accessing them, methods, and the modern shorthand syntax you'll see in almost every codebase.

Object literals

The simplest way to create an object is an object literal: curly braces containing key: value pairs, separated by commas:

JS Your first objects

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A few things to notice:

  • Values can be anything: strings, numbers, booleans, arrays, other objects, even functions.
  • Objects can be nested, and you reach inner values by chaining: book.publisher.city.
  • A trailing comma after the last property is allowed, and most style guides recommend it because it makes adding lines cleaner.
  • Keys are strings (or symbols). You only need quotes around a key when it isn't a valid identifier, such as "first name" or "content-type".

Reading properties: dot vs bracket

There are two ways to access a property:

  • Dot notation: book.title. Short and readable. The key must be a valid identifier written directly in the code.
  • Bracket notation: book["title"]. The key is any expression that produces a string, so it can contain spaces or dashes, or come from a variable.
JS When you need brackets

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last two lines show the most common bracket mistake. stats.field means "the property named field", which doesn't exist. stats[field] evaluates the variable and uses its value, "wins", as the key.

Missing properties

Reading a property that doesn't exist isn't an error: you get undefined. But reading a property of undefined is an error. That's why deep access into data that might be incomplete often uses optional chaining:

JavaScript
const user = { name: "Ola" };

user.email;              // undefined
user.address.city;       // TypeError: can't read 'city' of undefined
user.address?.city;      // undefined, no error

Keys are strings

Whatever you put inside the brackets, JavaScript converts it to a string (unless it's a symbol). So obj[1] and obj["1"] are the same property. This also means you can't use objects as keys: every object becomes the string "[object Object]". If you need non-string keys, use a Map.

Adding, changing and removing properties

Objects are mutable: you can add, change and remove properties at any time, using the same dot or bracket syntax:

JavaScript
const settings = { theme: "light" };

settings.theme = "dark";          // change
settings.fontSize = 16;           // add
settings["show tips"] = false;    // add with a key that needs brackets
delete settings.fontSize;         // remove

This works even when the object is stored in a const. As the Variables lesson explained, const stops you from reassigning the variable โ€” settings = {} throws โ€” but the object it points to can still change. To stop the object itself from changing, you need Object.freeze(), covered in Working with Objects.

Objects are stored by reference

A variable doesn't hold the object itself, but a reference to it. Assigning an object to another variable copies the reference, not the object, so both names point at the same thing:

JS Two names, one object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This also explains why functions can change objects you pass in, and why === compares objects by identity, not by contents. The lesson Copying Objects shows how to make real copies when you need them.

Methods

A property whose value is a function is called a method. Methods give objects behavior. Inside a method, this refers to the object the method was called on:

JS Methods and this

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The shorthand deposit(amount) { โ€ฆ } is the modern way to write methods. Avoid arrow functions for methods that use this, because arrows don't get their own this (see Arrow Functions).

Shorthand properties

When a property's value comes from a variable with the same name as the key, you can write the name once:

JavaScript
const name = "Mo";
const age = 31;

const longForm = { name: name, age: age };
const shortForm = { name, age };          // the same object

This is extremely common when building objects from variables or returning several values from a function: return { total, count, average };.

Computed keys

Sometimes the key itself must be calculated. Put an expression in square brackets on the left of the colon, and its value becomes the key:

JS Computed property names

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The ...record part copies the existing properties into the new object; that's spread syntax, which you'll meet properly soon.

Property order

When you list or loop over an object's keys, JavaScript uses a defined order: first all keys that look like non-negative integers ("0", "7", "42"), in ascending numeric order; then all other string keys, in the order they were added. That rule surprises people who use numeric IDs as keys:

JavaScript
const byId = { 30: "c", 4: "a", 12: "b", name: "x" };
Object.keys(byId); // ["4", "12", "30", "name"]

If insertion order matters for numeric-looking keys, use a Map or an array.

Objects or arrays?

Both group values, but they answer different questions. Use an array when you have a list of similar things in a meaningful order โ€” a playlist, search results, the steps of a recipe โ€” and you access them by position. Use an object when you have one thing described by named fields โ€” a song with a title, artist and length โ€” and you access values by name. Very often you combine them: an array of objects, where each object describes one item in the list. That shape is so common that most data you'll load from APIs looks exactly like it.

Objects or classes? Object literals are perfect for one-off data and configuration. When you need many objects with the same shape and methods, a class or a factory function avoids repeating the methods in every object.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given const key = "size";, which expression reads the property named size from item?

    Brackets evaluate the expression inside, so item[key] uses the value "size". item.key looks for a property literally named key.
  2. 2. Which property name requires bracket notation?

    A dash isn't allowed in an identifier, so obj["first-name"] is required. The others are valid identifiers.
  3. 3. What does const a = { n: 1 }; const b = a; b.n = 2; console.log(a.n); print?

    Both variables hold a reference to the same object. Changing it through b is visible through a; const only prevents reassignment.
  4. 4. With const city = "Oslo";, what does { city } create?

    Shorthand properties use the variable's name as the key and its value as the value.
  5. 5. What is ({ ["a" + 1]: true })?

    Square brackets around a key make it computed: the expression is evaluated and its result, "a1", becomes the key.

Summary

  • Objects store values under string (or symbol) keys; create them with { key: value } literals.
  • Use dot notation for fixed, valid names and bracket notation for computed keys, keys with special characters and keys stored in variables.
  • Missing properties give undefined; use ?. when an intermediate object might be missing.
  • Objects are mutable and stored by reference โ€” even in a const, and even when passed to a function.
  • Methods are function-valued properties; write them with method shorthand so this works.
  • Shorthand properties { name } and computed keys { [expr]: value } keep object-building code short.

Next: Working with Objects โ€” listing, transforming, merging and protecting object properties.