Skip to content

JavaScript Objects

An object groups related values under names. Each name and its value make a property, and the object is written as a list of properties inside curly braces, which is called an object literal. Where an array suits an ordered list of similar things, an object suits one thing described by several named values.

A property is read with dot notation or with bracket notation, where the name goes in quotes inside square brackets:

const book = {
title: 'Middlemarch',
author: 'George Eliot',
pages: 880,
};
console.log(book.title);
console.log(book['author']);
console.log(book.year);

This prints:

Middlemarch
George Eliot
undefined

Reading a property that does not exist gives undefined rather than an error, so a typo in a property name fails quietly.

Assigning to a property creates it if it is missing and replaces its value if it is already there. Bracket notation is needed when the name is not a valid identifier, for example when it contains a space:

const book = { title: 'Middlemarch', author: 'George Eliot', pages: 880 };
book.year = 1871;
book['on loan'] = false;
book.pages = 904;
console.log(book);

This prints:

{
title: 'Middlemarch',
author: 'George Eliot',
pages: 904,
year: 1871,
'on loan': false
}

const stops the variable book being pointed at a different object, but it does not stop the object’s properties changing. Bracket notation also accepts a variable or any expression as the name, which Dynamic Object Properties covers.

A list of records is usually an array of objects. The array index picks the object, and a property access then picks the value inside it:

const shelf = [
{ title: 'Middlemarch', author: 'George Eliot' },
{ title: 'Persuasion', author: 'Jane Austen' },
];
shelf.push({ title: 'Bleak House', author: 'Charles Dickens' });
shelf[1].year = 1817;
console.log(shelf.length);
console.log(shelf[1]);
console.log(shelf[2].author);

This prints:

3
{ title: 'Persuasion', author: 'Jane Austen', year: 1817 }
Charles Dickens

push adds the new object to the end of the array. Each object can carry its own properties, so only the second book has a year.

A variable holds a reference to an object, not a copy of it. Assigning the object to a second variable gives two names for the same object, and two objects with the same properties are still different objects:

const original = { title: 'Persuasion', copies: 2 };
const sameBook = original;
sameBook.copies = 3;
console.log(original.copies);
const lookalike = { title: 'Persuasion', copies: 3 };
console.log(original === sameBook, original === lookalike);

This prints:

3
true false

To make a separate copy, use Object.assign() or spread syntax, which Object.assign() describes. Pass by Reference shows what this means for objects passed to functions.

Steve Griffith covers this topic in his video Playing with JavaScript Objects.