JavaScript Object Type

Insertion/modification

The syntax for insertion and modification is almost identical to the one we used for extraction with the only difference being the equal symbol and the value on the right side.

const book = {}
// dot notation
book.title = "Towers of Midnight"
console.log(book.title) // "Towers of Midnight"
// dynamic key
let key = "authors"
book.authors = ["Robert Jordan", "Brandon Sanderson"]
console.log(book[key]) // ["Robert Jordan", "Brandon Sanderson"]

Do note that the insertion syntax is identical to the modification syntax, so we could potentially end up modifying an already existing property with a value. Which isn't always desirable. In situations like those we can use the method hasOwnProperty to first check if the object has set a value for the property before modifying the value.

Functional insertion/modification

We can use the spread operator to modify or insert properties without mutating the original object. Properties from the original object will be copied to the new array, and all new properties we add will be reflected in the object returned.

const book = {
title: "The Dragon Reborn"
}
const bookWithYear = {
...book,
year: 1991
}
// book is left unmodified
console.log(book.title) // "The Dragon Reborn"
console.log(book.year) // undefined
// bookWithYear has all the properties from book
// plus those we added
console.log(bookWithYear.title) // "The Dragon Reborn"
console.log(bookWithYear.year) // 1991