How to Add Items to an Object with Vanilla JavaScript

In JavaScript there are two ways add items to an object:

  1. Dot dotation: object.thingToAdd
  2. Bracket notation: object['thingToAdd'

Dot notation

Lets look at dot notation first:

let dog = {
  name: "Naya",
  age: "2",
  color: "black",
}

// Add item to dog object
dog.breed = "Rottweiler mix"

// Log object to console
console.log(dog)
// { name: "Naya", age: "2", color: "black", breed: "Rottweiler mix", }

That’s dot notation.

Bracket notation

Bracket notation has fewer limitations on how you can add properties to an object. Let’s look at the same dog object from before:

let dog = {
  name: "Naya",
  age: "2",
  color: "black",
}

Now let’s add a property and value to it with bracket notation:

dog["weight"] = "34kg"

console.log(dog)
//  { name: "Naya", age: "2", color: "black", weight: "34kg", }

As you can see, it works exactly the same as with dot notation — in this specific example.

Now let’s compare the two methods.

Dot notation vs. bracket notation

Try to add a number as the new property name by using dot notation:

// Dot notation
dog.1 = "Property 1"
console.log(dog)
// Uncaught SyntaxError: Unexpected number

Whoops, you get an error! That’s because with dot notation you can’t use numbers in property names.

But you can use numbers with bracket notation, as long as your identifer is formatted as a string:

// Bracket notation
dog["1"] = "Property 1"
console.log(dog)
// { 1: "Property 1", age: "2", color: "black", name: "Naya" }

Again, bracket notation is more flexible than dot notation.

Which should you use?

It is a good practice to use dot notation whenever you can since it is easier to read. But whenever you have to add a property to an object, and the property needs to start with a number, special symbol, or any reserved keyword, then use bracket notation.

Dot notation:

  • Property identifiers (names) and only contain alphanumeric (a—z) characters, underscore (_), or $.
  • Property identifiers cannot start with a number.
  • Property identifiers cannot contain variables.

Bracket notation:

  • Property identifiers (names) have to be a string value type or a variable that references a string.
  • You can use spaces on identifiers [" property"],
  • String identifiers can start with numbers ["1st"]

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on