Objects in JavaScript
Tags: javascript
Published: 2020-07-10 19:06:22

---
title: Objects in JavaScript
published: true
date: 2020-07-08 06:00:00 UTC
tags: javascript
canonical_url: https://www.prestonlamb.com/blog/objects-in-javascript
---

## [tldr;](#tldr)

Objects are used in JavaScript applications all the time, and understanding how to create them, work with them, and use them is vital. In this post we’ll talk about how to create objects, access their keys, freeze objects, loop over the keys in an object, and convert objects to a string. By the end of the post, you should have a good idea of how best to use objects in your application.

## [Creating New Objects](#creating-new-objects)

Let’s start with the basics of creating objects. The easiest way to do this is to declare a variable and initialize it to an object like this:

```js
const myObj = {};
```

In that example, we initialized the variable to an empty object. It’s that simple! But you wouldn’t normally initialize a variable to an empty object, so let’s add some data to the object. You add data to objects in key-value pairs. That means that on the left is the key (or attribute) name and on the right is the value. The keys and values are separated by colons. Here’s an example:

```js
const dog = {
  name: 'Duke',
  breed: 'Labradoodle',
};
```

In the above example, I have two keys: `name` and `breed`. The values for those keys are “Duke” and “Labradoodle”, respectively.

The other thing about objects and the data they can store is that the value of a key can be another object, or an array, or a string, or a number, or whatever you want to store there. Objects can literally hold anything you want inside of them. The versatility is really useful when building applications. Here’s one more example of an object storing different types of data:

```js
const person = {
  name: {
    first: 'Preston',
    last: 'Lamb',
  },
  hobbies: ['coding', 'reading', 'basketball'],
};
```

One thing to know about object keys is that they can’t have dashes or spaces in the name of the key unless the key is declared and wrapped in single or double quotes:

```js
const person = {
  'first-name': 'Preston',
  'last-name': 'Lamb',
};

console.log(name['first-name']);
console.log(name['last-name']);
```

You’ll find as you build applications that you will store all sorts of data in objects. They’re flexible, versatile, and easy to work with.

## [Accessing Keys](#accessing-keys)

After you create an object, how do you access the keys on the object to get the values? There are two ways that you can do this: dot notation and bracket notation. Let’s start with dot notation. When using dot notation, you put the name of the variable, a period, and then the name of the key:

```js
const dog = {
  name: 'Duke',
};

console.log(dog.name); // Duke
```

That’s it. You’ve probably seen this being done before. Another way to access the the value of a key on an object is the bracket notation. Here’s an example of that:

```js
console.log(dog['name']); // Duke
// OR
const attribute = 'name';
console.log(dog[attribute]); // Duke
```

With bracket notation, you just need to put a string inside brackets right after the name of the object. The string should match an attribute on the object, otherwise you’ll get `undefined` returned. If the key name has a hyphen in it, you need to use bracket notation. Otherwise it’s you’re choice.

## [Freezing Objects](#freezing-objects)

After you’ve created an object, there’s nothing that can stop you from adding keys to the object, deleting keys from it, or editing the value of existing keys. If you use the `const` keyword, you can prevent the location in memory where the object is stored from changing, but the object can still be changed. You might remember that from [this post on variables and storing by reference](/blog/javascript-variables-value-and-reference#reference). Luckily, there is a built in function for us to help, and it’s called the `freeze` method. For it to work as expected, though, you need to remember to put your file in strict mode. Here’s an example of using the freeze method:

```js
'use strict';

const pizza = {
  name: 'Pepperoni',
  price: 7,
  ingredients: ['cheese', 'pepperoni'],
};

Object.freeze(pizza);

pizza.name = 'Pepperoni Pizza'; // Cannot assign to read only property 'name' of object
delete pizza.price; // Cannot delete property 'price' of object

pizza = {
  name: 'Pepperoni',
  price: 7,
  ingredients: ['cheese', 'pepperoni', 'marinara'],
}; // Assignment to constant variable
```

So as long as you’re running your file in strict mode, Object.freeze should help prevent objects in your application from being changed. You might want to freeze an object that holds some configuration that shouldn’t change, for example.

One thing to note though is that if you don’t use `const`, JavaScript will allow you to reassign the value of the variable. That essentially means you have changed the values of the object and it nullifies what Object.freeze does, but if you use `const` along with `freeze` you should be good to go.

## [Working with Object Keys](#working-with-object-keys)

Sometimes you may need to loop over the keys in an object. And in this case I’m not talking about getting the values referenced by the keys, but the actual keys themselves. Or maybe you need to see if the object passed in to your function is an empty object, or if it’s got data stored in it. There are a couple ways to do this (see [the for … in loop](/blog/javascript-loops#for-in)) but now we’re going to look at using the `Object` class to do this.

The `Object` class has a method on it called `keys` which allows you to more easily work with the keys of an object by converting the keys to an array. Let’s look at an example:

```js
const dog = {
  name: 'Duke',
  breed: 'Labradoodle',
  age: 3,
};

console.log(Object.keys(dog)); // ['name', 'breed', 'age']
console.log(Object.keys(dog).length); // 3
```

In this example we have a dog object. We call the `keys` method on the `Object` class, and pass our `dog` object into the method. The return value is an array with the three keys on the object; name, breed, and age. In the second example, we call the same method but then immediately chain the `.length` property on to the call. The return value is 3, as there are three keys on the object.

Because the return value of this method is an array, we can now use [the for … of loop](/blog/javascript-loops#for-of) to loop over the array:

```js
for (const key of Object.keys(dog)) {
  console.log(key); // name, breed, age
}
```

There’s no real difference between the `for ... in` loop and `for ... of` after using the `Object.keys` method. It really just comes down to personal preference.

## [Converting Objects to Strings and Back](#converting-objects-to-strings-and-back)

Now and then you may need to convert an object to a string. I mainly use it for debugging purposes. My favorite way to do this is to use the `JSON.stringify` method. The simplest way to do this is like this:

```js
const dog = {
  name: 'Duke',
  breed: 'Labradoodle',
  age: 3,
};

console.log(JSON.stringify(dog)); // { name: 'Duke', breed: 'Labradoodle', age: 3 }
```

All you need to do is pass the object into the `JSON.stringify` method and it’ll be converted to a string. There are a couple options you can pass as well to the function. Instead of printing it out in the console on a single line, you can print it out on multiple lines, with indentation, like this:

```js
const dog = {
  name: 'Duke',
  breed: 'Labradoodle',
  age: 3,
};

console.log(JSON.stringify(dog, null, 2));
```

The output is similar to the previous example, but on multiple lines with indentation. When debugging, it makes it much easier to read what’s on the object. Again, I passed the object as the first argument, the second is a function that will replace attributes on the object or an array of keys that you want to print out (I passed `null` in this case) and the third argument is the amount of indentation space desired.

Let’s look at an example of passing a value for the second argument. In this case, I’m going to pass an array of keys that I want to be output in the result. If the key is not included in the array, it won’t be returned in the resulting string. A good use case for this is if you don’t want to print out a social security number, for example:

```js
const person = {
  name: 'John Smith',
  ssn: 12345689,
};

console.log(JSON.stringify(person, ['name'])); // { name: 'John Smith' }
```

Just like you may need to convert objects to strings, it can be just as useful to go the other way and convert a string to an object. Sometimes data comes back from an API as a string, but it’s so much easier to work with as an object or array. The `JSON.parse` method is perfect for this. Here’s an example:

```js
const dogStr = "{ name: 'Duke', age: 3 }";
const dogObj = JSON.parse(dogStr);

console.log(dogObj); // { name: 'Duke', age: 3 }
console.log(dogObj.name); // Duke
```

The same result can be seen if the contents of the string are in array form. You will get an error if you don’t pass in an object or an array, though, so be aware of that.