What is a JavaScript object?

An object groups related values under named properties. For example, a book can have a title, an author, and a page count. To try the examples in this article, you need a browser developer console that supports JavaScript ES2015 or later. Open the console, enter one example at a time, and check the result. No packages or project setup are required.

Create a book with an object literal: const book = { title: 'The Quiet Garden', author: 'Mira Lee', pages: 120 }; The names on the left are property keys; the values on the right are the data stored under those keys. Here, title and author hold strings, while pages holds a number. An object can also hold arrays, other objects, or functions.

You can read a property with dot notation: book.title returns 'The Quiet Garden', and book.pages returns 120. Dot notation is a good default when you know the property name while writing the code and that name is a valid identifier. Keep the book object in your console for the examples that follow.

Adding and changing properties

You can change a property by assigning a new value: book.pages = 124; Afterward, book.pages returns 124. You can add a property the same way: book.available = true; Now book has an available property as well. Although book was declared with const, its properties can still change. const prevents you from assigning a different object to the variable book; it does not freeze the object.

Reading a property that does not exist usually gives undefined. For example, book.publisher returns undefined until you add that property. Be careful, though: a property can also exist and deliberately contain undefined. If you need to distinguish those cases, you can check whether the object owns the property with Object.prototype.hasOwnProperty.call(book, 'publisher'). This expression returns false until publisher has been added directly to book.

For a small collection of related facts, an object is often clearer than separate variables such as bookTitle, bookAuthor, and bookPages. Clear property names also make later code easier to understand. Choose names that describe what the values mean, not merely what type they hold.

When to use bracket notation

Bracket notation reads a property by using an expression between square brackets. With a quoted key, book['title'] returns the same value as book.title. Brackets are especially useful when the key is stored in a variable: const field = 'author'; book[field] returns 'Mira Lee'. In contrast, book.field looks for a property literally named field. It does not use the value inside the field variable.

Bracket notation also works for keys that cannot be written after a dot. For example: book['print-edition'] = 2; You can then read book['print-edition']. Writing book.print-edition would not mean the same thing; JavaScript would interpret the hyphen as a subtraction operator. Spaces and other special characters in property names are another reason to use brackets.

A useful rule is to use dots for fixed, ordinary property names and brackets for computed or unusual names. If a key comes from user input, check that it is one your program expects before using it to change an object. Otherwise, a typo or unexpected value may create a property you never intended to add.

Methods: functions stored on objects

A method is a function stored as an object property. Make a separate example in your console: const counter = { count: 0, increment() { this.count += 1; return this.count; } }; Calling counter.increment() returns 1. Calling it again returns 2. The method changes the count property and returns its new value.

In this call, this refers to counter, the object used to call the method. That makes this.count a way for the method to work with its object's data. How a function is called matters: if you save the method as const addOne = counter.increment; and then call addOne(), it no longer has the same object call context. For a beginner's first methods, call them through the object, as in counter.increment().

A method can read other properties too. For example: const person = { name: 'Sam', greet() { return 'Hello, ' + this.name; } }; Calling person.greet() returns 'Hello, Sam'. The method syntax is short, but it still creates a function stored under the greet key.

A small practice exercise

Try making an object for a task: const task = { label: 'Read a chapter', done: false }; Read task.label with dot notation, then read it again with task['label']. Next, set const key = 'done'; and compare task[key] with task.key. The first reads the done property and returns false; the second looks for a property named key and returns undefined.

Finally, add a method: task.complete = function() { this.done = true; }; Call task.complete(), then inspect task.done. It should now be true. If you get an unexpected result, check whether you used a quoted property name or a variable inside the brackets, and whether you called the method through task. Those two details account for many early object mistakes.

Back to category ↗