Objects
Objects serve to describe and group the characteristics of an entity such as a user, a book, a product, etc. Objects are also called dictionaries, that is, they contain terms (properties) and their definitions (values).
Object creation
For declaration purposes, use object literals in curly braces {}
.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
isPublic: true,
rating: 8.38,
};
When you create an object, you can add properties, each of which is described by
key:value
pairs. The key is also called a property name, and it is always a
string. Property values can be of any type: primitives, arrays, objects,
booleans, functions, etc. Properties are separated by commas.
Key naming rules are simple:
- If the key is enclosed in quotes, it can be an arbitrary string.
- If there are no quotes, then restrictions apply: a name without spaces,
beginning with a letter or the characters
_
and$
.
Nested properties
Property value can be another object in order to store nested and grouped data. For example, the statistics of a social network user consists of the number of followers, views and likes, and it is most convenient to store this data as an object. The same is with the user's location: country and city separately.
const user = {
name: "Jacques Gluke",
tag: "jgluke",
location: {
country: "Jamaica",
city: "Ocho Rios",
},
stats: {
followers: 5603,
views: 4827,
likes: 1308,
},
};
Later, this can be used to search for users by country, city, minimum or maximum number of followers, etc.
Dot notation to access properties
The first way to access a property of an object is with the
object.property_name
syntax. Such dot notation is used in most cases and works
fine when you know in advance the name (key) of the property you want to access.
- The value of the property with a given name will be returned.
- If the object does not have a property with such name, you will be returned
undefined
.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
isPublic: true,
rating: 8.38,
};
const bookTitle = book.title;
console.log(bookTitle); // 'The Last Kingdom'
const bookGenres = book.genres;
console.log(bookGenres); // ['historical prose', 'adventure']
const bookPrice = book.price;
console.log(bookPrice); // undefined
Accessing nested properties
To access nested properties, a reference string with dot notation is used. For
example, if you need to get the value of the user's country, write
user.location.country
, where user.location
is a reference (path) to the
object in the location
property, and user.location.country
is a reference to
the country
property in this object. That is, the "dot" indicates the
following nesting.
const user = {
name: "Jacques Gluke",
tag: "jgluke",
location: {
country: "Jamaica",
city: "Ocho Rios",
},
hobbies: ["swimming", "music", "sci-fi"],
};
const location = user.location;
console.log(location); // object location
const country = user.location.country;
console.log(country); // 'Jamaica'
If the property value is an array, user.hobbies
from our example is a
reference to this array. Then you can access its elements through square
brackets and index, or use properties and methods.
const hobbies = user.hobbies;
console.log(hobbies); // ['swimming', 'music', 'sci-fi']
const firstHobby = user.hobbies[0];
console.log(firstHobby); // 'swimming'
const numberOfHobbies = user.hobbies.length;
console.log(numberOfHobbies); // 3
Accessing properties through square brackets
The second way to access a property of an object is with the
object["property name"]
syntax. It looks like referring to an array element,
but in the brackets you indicate not the element's index, but the property name
as a string.
The "square brackets" syntax is used much less often, e.g. when the property name is unknown or stored in a variable, for example, as a function parameter value.
- The value of the property with a given name will be returned.
- If the object does not have a property with such name, you will be returned
undefined
.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
isPublic: true,
rating: 8.38,
};
const bookTitle = book["title"];
console.log(bookTitle); // 'The Last Kingdom'
const bookGenres = book["genres"];
console.log(bookGenres); // ['historical prose', 'adventure']
const propKey = "author";
const bookAuthor = book[propKey];
console.log(bookAuthor); // 'Bernard Cornwell'
Property value change
After the object is created, you can change its property values. To do this, you need to refer to them by name, for example, using dot notation, and assign a new value.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
isPublic: true,
rating: 8.38,
};
book.rating = 9;
book.isPublic = false;
book.genres.push("drama");
console.log(book.rating); // 9
console.log(book.isPublic); // false
console.log(book.genres); // ['historical prose', 'adventure', 'drama']
Adding properties
The operation of adding a new property after object creation is no different from changing the value of an existing property. If, when writing a value by name, no such property exists in the object, it will be created.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
isPublic: true,
rating: 8.38,
};
book.pageCount = 836;
book.originalLanguage = "en";
book.translations = ["ua", "ru"];
console.log(book.pageCount); // 836
console.log(book.originalLanguage); // 'en'
console.log(book.translations); // ['ua', 'ru']
Shorthand properties
Sometimes, when creating an object, you need to take the property value from a variable or function parameter of the same name as the property.
The syntax in the following example is too awkward because you have to duplicate the name of the property and the name of the variable that stores the required value.
const name = "Henry Cibola";
const age = 25;
const user = {
name: name,
age: age,
};
console.log(user.name); // "Henry Cibola"
console.log(user.age); // 25
The shorthand properties syntax solves this problem by allowing the variable name to be used as the property name and its value as the property value.
const name = "Henry Cibola";
const age = 25;
const user = {
name,
age,
};
console.log(user.name); // "Henry Cibola"
console.log(user.age); // 25
That is, when declaring an object, it is enough to enter only the property name, and the value will be taken from a variable with the same name.
Computed properties
In some cases, when declaring an object, you need to add a property with a name that you do not know, as it is stored as the value of a variable or as the result of a function.
Previously, you needed to create an object and then add properties through square brackets, which is not very convenient.
const propName = "name";
const user = {
age: 25,
};
user[propName] = "Henry Cibola";
console.log(user.name); // 'Henry Cibola'
The computed properties syntax helps you avoid unnecessary code and, in some cases, simplify it. The value of a computed property can be any valid expression.
const propName = "name";
const user = {
age: 25,
// The name of this property will be taken from the value of the variable propNam
[propName]: "Henry Cibola",
};
console.log(user.name); // 'Henry Cibola'
Object methods
Until now, we have considered objects only as stores of interrelated data, for example, information about a book, etc. Storage objects are usually located in an array of similar objects, which represents a collection of similar items.
Objects can store not only data, but also functions for working with this data, i.e. methods. If the property value is a function, such property is called an object method.
// ✅ Entities grouped logically and syntactically
const bookShelf = {
books: ["The Last Kingdom", "Dream Guardian"],
// This is an object method
getBooks() {
console.log("This method will return all books, the books property");
},
// This is an object method
addBook(bookName) {
console.log("This method will add a new book to the books property");
},
};
// Method calls
bookShelf.getBooks();
bookShelf.addBook("New book");
Such objects can be called "models". They couple data with methods to work with
that data. For example, you could declare the variable books
and two
functions, getBooks()
and addBook(bookName)
, but then they would be three
independent entities without an explicit syntactic and with a weak logical
connection.
// ❌ Loosely coupled, independent entities
const books = [];
function getBooks() {}
function addBook() {}
Accessing object properties in methods
Methods are used to work with object properties and change them. To access an
object, the method does not use the variable name, for example, bookShelf
, but
the keyword this
, the context. The value of this
will be the object before
"dot", that is, the object that called this method, in our case it is a
reference to the bookShelf
object.
const bookShelf = {
books: ["The Last Kingdom"],
getBooks() {
console.log(this);
},
};
// Dot is preceded by the bookShelf object,
// so when the method is called, this will store a reference to it.
bookShelf.getBooks(); // {books: ['The Last Kingdom'], getBooks: f}
In order to access the properties of an object in methods, we refer to it
through this
and then, as usual, to its properties using dot notation.
const bookShelf = {
books: ["The Last Kingdom"],
getBooks() {
return this.books;
},
addBook(bookName) {
this.books.push(bookName);
},
removeBook(bookName) {
const bookIndex = this.books.indexOf(bookName);
this.books.splice(bookIndex, 1);
},
};
console.log(bookShelf.getBooks()); // ["The Last Kingdom"]
bookShelf.addBook("The Mist");
bookShelf.addBook("Dream Guardian");
console.log(bookShelf.getBooks()); // ['The Last Kingdom', 'The Mist', 'Dream Guardian']
bookShelf.removeBook("The Mist");
console.log(bookShelf.getBooks()); // ['The Last Kingdom', 'Dream Guardian']
Why not to use the object name when accessing its properties? We are not going to change it anyway. However, the object name is unreliable, you can copy the methods of one object into another (with a different name), and later you will find out that often, when creating an object, you do not know the name at all. When using this, you ensure that the method works with the object that called it.

We will learn more about the keyword this
and all its stumbling blocks in the
next lessons, but for now it is enough to simply use this
when referring to
object properties in its methods.