DEV Community

Preston Lamb
Preston Lamb

Posted on • Originally published at prestonlamb.com on

Objects in JavaScript

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

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:

const myObj = {};
Enter fullscreen mode Exit fullscreen mode

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:

const dog = {
  name: 'Duke',
  breed: 'Labradoodle',
};
Enter fullscreen mode Exit fullscreen mode

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:

const person = {
  name: {
    first: 'Preston',
    last: 'Lamb',
  },
  hobbies: ['coding', 'reading', 'basketball'],
};
Enter fullscreen mode Exit fullscreen mode

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:

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

console.log(name['first-name']);
console.log(name['last-name']);
Enter fullscreen mode Exit fullscreen mode

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

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:

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

console.log(dog.name); // Duke
Enter fullscreen mode Exit fullscreen mode

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:

console.log(dog['name']); // Duke
// OR
const attribute = 'name';
console.log(dog[attribute]); // Duke
Enter fullscreen mode Exit fullscreen mode

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

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. 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:

'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
Enter fullscreen mode Exit fullscreen mode

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

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) 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:

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

console.log(Object.keys(dog)); // ['name', 'breed', 'age']
console.log(Object.keys(dog).length); // 3
Enter fullscreen mode Exit fullscreen mode

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 to loop over the array:

for (const key of Object.keys(dog)) {
  console.log(key); // name, breed, age
}
Enter fullscreen mode Exit fullscreen mode

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

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:

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

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

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:

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

console.log(JSON.stringify(dog, null, 2));
Enter fullscreen mode Exit fullscreen mode

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:

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

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

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:

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

console.log(dogObj); // { name: 'Duke', age: 3 }
console.log(dogObj.name); // Duke
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
supermario_ai profile image
SuperMario

Love this format, digestible, byte-sized chunks! 😉