Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Table of Contents

Adding and Removing Properties on an Object

by kirupa   |   filed under JavaScript 101

Objects in JavaScript seem fairly simple. They have a name, they use the weird curly braces a lot, and they contain data in the form of property / value pairs:

let superHero = {
  firstName: "Tony",
  lastName: "Stark",
  misc: {
    color: "Red",
    name: "Iron Man",
    affiliate: "Stark Industries"
  }
};

As we have seen in other tutorials, there is more to our friendly JavaScript objects than meets the eye. In this tutorial, we'll look at something that seems pretty straightforward - adding and removing properties from objects. We'll see just how straightforward (or not) this is in a few moments.

Onwards!

Adding Properties

Once you have an object, there are several paths you can take to add additional properties on it. The path we will take is a simple and performant one that uses the array-like bracket notation with your new property name acting as the index.

Let's say we have an object called colors that looks as follows:

let colors = {
  header: "blue",
  footer: "gray",
  content: {
    title: "black",
    body: "darkgray",
    signature: "light blue"
  }
}

We want to add a new property called logo and give it a value of transparent. The way we would add this property is as follows:

colors["logo"] = "transparent";

That's all there is to it. Once you have added this property, you can access it using one of two approaches:

// Approach 1
let logoColor = colors["logo"];

// Approach 2
let logoColor = colors.logo;

It doesn't matter which approach you take. Use whichever makes you (or your team) happy. I tend to favor the second approach with the dot notation, for it is consistent with how we typically access the value of a property. The exception is when you might need to dynamically generate the property name:

let numbers = [0, 1, 2, 3, 4];

for (let i = 0; i < numbers.length; i++) {
  let objValue = myObject["data" + numbers[i]];
  console.log(objValue);
}

In those cases, the first approach is the one that makes the most sense. There aren't any recommended ways (please don't use eval) you can use the second approach with a property name that needs to be created on the fly.

Before we wrap this section up, there is just one more detail about adding properties that we will look at. If you want to add a property to another object that lives within your object (aka a nested object), you combine everything we've seen here to do this. For example, let's say we want to add a property called frame to the object stored by the content property in our colors object:

let colors = {
  header: "blue",
  footer: "gray",
  content: {
    title: "black",
    body: "darkgray",
    signature: "light blue"
  }
}

The way we can do that is as follows:

colors.content["frame"] = "yellow";

If you prefer to use the bracket notation for accesing the content property, you can do this instead:

colors["content"]["frame"] = "yellow";

Before we wrap this up, I mentioned at the beginning that you have several paths that you can take to add properties to an object. We looked at one such path. A more complex path that you can take could involve the Object.defineProperty and Object.defineProperties methods. These methods allow you to set a property and its value, but they allow you to do much more like define getters/setters, specify whether a property can be enumerated, specify whether a property can be customized, and more. It's definitely overkill for what you will want to do 99% of the time, but know this: if overkill is what you want, then these two methods deliver. The MDN documentation does a good job providing examples of how you can use them to add one or many properties to an object.

Removing Properties

If you thought adding properties to an object was fun, removing properties from an object is a bit boring. It is also simpler. Let's continue to work with our colors object:

let colors = {
  header: "blue",
  footer: "gray",
  content: {
    title: "black",
    body: "darkgray",
    signature: "light blue"
  }
}

What we want to do is remove the footer property. We have two ways of doing this depending on whether we want to access the footer property using the bracket notation or whether we want to access it using the dot notation:

delete colors.footer;

// or

delete colors["footer"];

The key to making this all work is the delete keyword. Simply use the delete keyword and follow it up with the property you'd like to remove. That's all there is to it.

Now, this wouldn't be JavaScript if I didn't mention a caveat. This one has to do with performance. If you will be deleting a lot of properties on a frequent basis across a large number of objects, delete is much slower than just setting the value of the property to something like undefined:

colors.footer = undefined;

// or

colors["footer"] = undefined;

The flipside is that setting a property to undefined means the property still exists in memory. You'll need to calculate the tradeoffs (speed vs. memory) in your situation and optimize for the one that makes the most sense for you.

Conclusion

Anyway, there is actually a whole lot more we can talk about here. For example, ES6 introduces some crazy new ways of dealing with properties inside an object, and some of them do change how we can add and remove properties as well. Like with any good story, the trick is knowing when to stop. Clearly, I have much to learn.

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2024 //--