Objects in JavaScript: Creating, Accessing and Updating Values

Objects in JavaScript are used to group together a set of variables and functions to create a representation of something from the real world.

The following is an object representing a hotel, featuring five properties and one method. Enclosed in curly braces, it's stored within a variable named hotel

Object representation

Within an object, variables and functions are named differently.

If a variable is a part of an object, it's called a property. Properties provide information about the object, such as the name of a hotel or the number of rooms it has. Different hotels may have different names and room counts.

When a function is part of an object, it's known as a method. Methods represent actions associated with the object. For example, you can find available rooms by subtracting booked rooms from the total.

Similar to variables and named functions, properties and methods also have names and values. In an object, this name is called a key. An object can't possess two keys with the same name, as keys are used to access their corresponding values.

Property values can be strings, numbers, Booleans, arrays, or even other objects. Method values are always functions.

The above hotel object contains the following key/value pairs:

key/value pairs of Hotel Object

Creating an object: Literal notation

There are multiple ways to construct objects. The simplest and most commonly used method is literal notation.

Let’s look at the same hotel object we have seen earlier.

Hotel Object

The object is the curly braces and their contents. The object is stored in a variable called hotel , so you would refer to it as hotel object.

To establish key-value pairs within the object, you need to use a colon. Properties and methods are separated by commas, except for the last one.

When setting the properties, treat the values like you would do for variables: strings in quotes, arrays in square brackets etc.

In the checkAvaibility() method, the this keyword is used to indicate that it is using the rooms and booked properties of this object.

Accessing an object

To access a property or method of an object, use the object's name, then a dot, and finally the property or method's name you wish to access. This is referred to as dot notation.

The dot itself is called the member operator. The property or method on the right side is a member of the object on the left.

In the example below, two variables are created to store the hotel name and the number of vacant rooms.

Accessing properties using dot notation

You can also access an object's properties (but not its methods) using square bracket syntax.

In this case, use the object's name followed by square brackets containing the property's name.

Accessing properties using square brackets

This notation is primarily used in two common scenarios:

  • When the property name is a number (technically possible, but it's generally better to avoid)
  • When a variable is utilized as a replacement for the property name (we'll explore this approach in some other article).

Creating an object: Constructor notation

To begin, you create a new object by using a combination of new keyword and the Object() constructor function. (This function is inherent to JavaScript and is employed for object creation.)

Once the blank object is created, you can add properties and methods to it using dot notation. Each statement that adds a property or method should end with a semicolon.

Creating an object: Constructor notation

This syntax can also be employed to append properties and methods to any object, regardless of the notation used for its creation.

For creating an empty object via literal notation, use

let hotel = {};

The curly braces indicate an empty object.

Updating an object

To update a property, you can use the dot notation that we discussed in the previous section to add properties to the object, but give it a new value.

If the object doesn't have the property you're trying to update, it will be added to the object.

hotel.name = 'Sunrise';

You can also update the properties of an object (but not its methods) using the square method syntax. The object name is followed by square brackets, and the property name is inside them.

A new value for the property is added after the assignment operator. Again, if the property you are attempting to update does not exist, it will be added to the object.

hotel['name'] = 'Sunrise';

To delete a property, use the delete keyword followed by the object's name and the property's name.

delete hotel.name;

If you wish to only clear a property's value, you can set it to an empty string.

hotel.name = ' ';

Creating many objects: Constructor notation

Sometimes you want several objects to represent similar things. Object constructors can use a function as a template for creating objects.

Begin by creating a template containing the object's properties and methods.

In this case, a function called Hotel serves as a blueprint for creating fresh objects that depict hotels. Like any function, it includes statements, which in this context, add properties or methods to the object.

Constructor notation

The function has three parameters. Each one sets the value of a property in the object. The methods will be the same for each object created using this function.

The this keyword is used instead of the object name to indicate that the property or method belongs to the object that this function creates.

Each statement that creates a new property or method for this object ends in a semicolon. (not a comma, which is used in the literal syntax).

The name of a constructor function usually begins with a capital letter (unlike other functions, which tend to begin with a lowercase character). The uppercase letter is supposed to help remind developers to use the new keyword when they create an object using that function.

You create instances of the object by using the constructor function. The new keyword followed by a call to the function creates a new object. The properties of each object are given as arguments to the function.

Here, two objects are used to represent two hotels, so each object needs a different name. When the new keyword calls the constructor function, it creates a new object.

Each time it is called, the arguments are different because they are the values of the properties of each hotel. Both objects automatically get the same method defined in the constructor function.

const TritonHotel = new Hotel("Triton", 40, 25);
const SunriseHotel = new Hotel("Sunrise", 75, 17);

Even when many objects are created using the same constructor function, the methods stay the same because they access, update or perform a calculation on the data stored in the properties.

You might also want to use this technique if your code contains a very complex object that needs to be available but might not be used. The object is defined in the function, but it is only created if it is needed.

Recap: Ways to create objects

1. Create the object, then add properties & methods

In both these examples, the object is created on the first line. The properties and methods are then added to it afterwards.

Once you have created an object, the syntax for adding or removing any properties and methods from that object is the same.

Literal Notation

const hotel = {};

hotel.name = "Triton";
hotel.rooms = 40;
hotel.booked = 25;
hotel.checkAvailability = function () {
  return this.rooms - this.booked;
};

Object Constructor Notation

let hotel = new Object();

hotel.name = "Triton";
hotel.rooms = 40;
hotel.booked = 25;
hotel.checkAvailability = function () {
  return this.rooms - this.booked;
};

2. Create an object with properties & methods

Literal Notation

A colon separates the key/value pairs. There is a comma between each key/value pair.

const hotel = {
  name: "Triton",
  rooms: 40,
  booked: 25,
  checkAvailability: function () {
    return this.rooms - this.booked;
  },
};

Object Constructor Notation

The function can be used to create multiple objects. The this keyword is used instead of the object name.

function Hotel(name, rooms, booked) {
  this.name = name;
  this.rooms = rooms;
  this.booked = booked;
  this.checkAvailability = function () {
    return this.rooms - this.booked;
  };
}

var TritonHotel = new Hotel("Triton", 40, 25);
var SunriseHotel = new Hotel("Sunrise", 120, 77);

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda