An object is a datatype that holds information in the form of key value pairs. A good way to think of an object and its key value pairs is like a drawer full of labelled folders. The drawer represents the object itself, the folders represent the object’s keys, and the information inside the folders are the values that pair with the keys.

Each of these folders would need a label to identify it, which in the case of our object would be the string or number used as an identifier in the object’s key. When strings are used in keys they can be written with or without quotes. The values that pair with can hold any sort of information.

The simplest JavaScript object possible is as follows.

The code above is an empty JavaScript object. JavaScript objects are written using curly braces and contain a series of comma separated key value pairs. Objects can also be assigned to variables. If we waned to write an object to hold information about a pet we could do so as follows.

Accessing Object Information

The values stored in an objects keys can be accessed with either dot or bracket notation, as shown below. An exception to this is when the keys of an object are written using quotes they can only be accessed through bracket notation.

myPet[species]
//'dog'

Manipulating Objects

The same notation that is used to extract information from objects can also be used to add information to objects or update existing information.

const myPet = {
name: 'Baby',
species: 'dog',
age: 10,
likes: ['fetch', 'snuggling', 'belly rubs'],
color: 'gray',
dislikes: ['loud noises']
}

Information can be deleted from objects using the delete keyword, as follows.

/*const myPet = {
name: 'Baby',
species: 'dog',
age: 9,
likes: ['fetch', 'snuggling', 'belly rubs'],
color: 'gray'
}*/

Iterating through Objects

One way to iterate through the enumerable keys or values of an object is by using a for…in loop.

for (let element in object) {
console.log(element: object[element]);
}
// a: 1
// b: 2
// c: 3

Another way to iterate through the enumerable keys or values of an object is by using the Object.keys() method.

for (let element of Object.keys(object)) {
console.log(element: object[element]);
}
// a: 1
// b: 2
// c: 3

Full Stack Software Engineer/ Web Developer and former Mechanical Engineer https://www.linkedin.com/in/ariel-jakubowski/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store