JavaScript Objects

Ariel Jakubowski
2 min readFeb 24, 2021

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.

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

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.name
//'Baby'
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.

myPet.color = 'gray'
myPet[dislikes] = ['loud noises']
myPet.age = 10
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.

delete myPet.dislikes/*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.

const object = { a: 1, b: 2, c: 3 };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.

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

--

--