Objects

Follow along with code examples here!

Table of Contents:

Slides

The basics

  • Objects are a data type that can store multiple pieces of data as key:value pairs called properties

  • In other languages, they are referred to as dictionaries:

  • Objects are useful for storing collections of data related to a single "thing", like data about a user.

  • Objects can have arrays and other objects nested inside.

  • When creating an object, the quotes around the key name are optional, except when the key includes spaces or begins with a number:

Accessing Objects with Dot Notation and Bracket Notation

  • Object values can be accessed and/or modified using dot notation or bracket notation

Dynamic Properties Challenge

When the key name of a property is stored in a variable, we must use bracket notation (we can't use dot notation).

Complete the program below so that it lets users add words to the dictionary!

Solution

To complete this program, add the line dictionary[newWord] = definition; to the end

Iterating Over Objects

One of the key benefits of an Array is that we can easily iterate through its values with a for loop. This is possible because we can use the variable i to step through the indexes of the array.

An object doesn't have countable indexes though. And their keys aren't in any particular order.

To iterate through an object, we can turn the object into an array using Object.keys(obj) which returns an Array of the given object's keys. We can then loop through those keys and use them to access their associated values:

If we don't care about the keys, we can just get an array of the object's values with Object.values(obj):

Advanced Object Syntax

Object Shorthand Using Variables

When constructing an object from variables, it can be quite repetitive if the key name matches the variable name.

If we are storing the value held by a variable in a key with the same name as that variable, we can omit the : and just write the name of the variable:

This example makes a user object with the provided properties as well as some default values (isAdmin is false and an empty friends list).

This is the same syntax used when exporting "named exports":

Destructuring

Destructuring is the process of creating variables from an existing array/object. When destructuring an object, the variable names must match the property key names that you wish to extract. The order in which you list the property names doesn't matter.

This is the exact same syntax used when importing a "named import".

When an object is passed to a function, we will often destructure the object directly in the parameter list, letting us choose only the properties of the object that are relevant to the function:

Last updated