JavaScript Object Type

Extraction

We can get the value of a property by using the dot notation or the square brackets notation. We use the dot notation when the property name is static and the square brackets notation when the property name is dynamic.

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

A property with no associated value returns undefined.

const person = {
name: "Mat Cauthon"
}
console.log(person.age) // undefined

Destructuring assignment

As with arrays, we can also use destructuring assignments to extract specific properties out of an object and assign them to constants or variables. The rest operator ... is available for objects as well and all non-explicitly named properties are dumped here.

const person = {
firstName: "Rand",
lastName: "al'Thor",
favoriteColor: "Pink"
}
const { firstName, ...allOtherProperties } = person
console.log(firstName) // Rand
console.log(allOtherProperties) // {lastName: "al'Thor", favoriteColor: "Pink"}