Get AI Code Completions for Your IDE

Home   >   Tutorials   >   JavaScript   >   Objects in JavaScript explained

JavaScript - Objects in JavaScript explained

In JavaScript, an Object is a special kind of data type.

This article provides an introduction to one of JavaScript’s most important data types. One that is situated at the language core. This article also covers working with objects, demonstrating basic functionalities such as accessing an object property, adding and updating a property, deleting a property and invoking object methods.

Unlike the other seven primitive data types (Number, BigInt, String, Boolean, undefined, Symbol, and null), Objects are able to store multiple values. Furthermore, an object can contain a mixture of these primitive data types. This ability to collect multiple different types of information into a single item has made Objects extremely valuable, paving their way to becoming one of the fundamental elements of modern JavaScript.

With this unique ability to collect values together, we can use objects to describe anything we want to in code. Regardless of complexity, as long as we know how to describe the item we can represent it as an Object.

An Object’s data is stored in key:value pairs. These pairs are called properties. They are also referred to as methods or functions.

Let’s explore Objects using an example. Imagine that we want to represent a car in JavaScript. A car is a complex entity; It has many characteristics, features, and different capabilities.

The following code provides a simple description of a car:

const car1 = {
    manufacturer: 'Toyota',
    model: 'Yaris',
    year: 2019,
    color: 'blue',
    mileage: 14638,
    go: function drive(location) {
        return 'Driving to ' + location
    }
};

We can build out this description as much as we like, even down to the number and type of bolts used to hold the car together.

In the above example, an Object was initialized using the literal notation with six key:value pairs. Three of them have Strings for values, two have Numbers and one has a function.

The variable const car1 is a reference to the object’s data – it only points to the memory location where this data is actually stored. The variable itself does not store the value!

Literal notation Syntax

Objects built using literal notation have the following syntax:

const myObject = {

key: value,

}

The literal notation syntax includes the Object reference variable name (const myObject), an assignment operator, an opening curly bracket, a list of key: value pairs, and finally a closing curly bracket. This can be written on a single line of code, or across multiple lines as in the above example.

key: value pairs

Objects map string keys to values that can be of any data type. These values can be any of the primitive data types, or even other Objects (note: in JavaScript, arrays are also Objects). Collectively, these key-value pairs are the Object’s properties. When the value for a key is a function, it is called a method.

In the above example, the last key (go) has a function as its value, therefore “go” is a method on the object.

A colon (:) separates the key name and its value. Each pair is separated from the next by a comma (the last comma may be omitted).

An object can be initialized with zero pairs of keys and values if you so desire.

In addition to literal notation, we can also build Objects using an Object constructor.

Object Constructor Syntax

You can build a new Object using constructor syntax as follows:

const myObject = new Object();

myObect.propertyName = propertyValue;

The constructor syntax lets you first define your variable (const myObject) as a new Object(), and then set its properties in subsequent lines of code.

This syntax may be more difficult to read, and definitely requires more keystrokes to construct the same object. Let’s look at an example of building an object using constructor syntax:

const car2 = new Object();
car2.manufacturer = 'Honda';
car2.model = 'Civic';
console.log(car2);
// Expected output: {manufacturer: "Honda", model: "Civic"}

In the above example, const car2 is pointing to an object. The following two lines set its manufacturer and model properties. For every property added, the variable name (car2) + a dot (.) must be typed before the property name is set. Using this method, we can add as many properties as we like.

Working with Objects

In this section, we’ll explore how to access, add, update, delete, and invoke object properties.

 

Access Object properties

Let us take const car1 as an example.

There are two ways to access the Object’s properties:

1. Dot notation

Dot notation simply consists of adding a dot (.) after the object name, then the name of the property you wish to access:

console.log(car1.manufacturer);
// Expected output: Toyota

Syntax

objectName.propertyName

In the example above, car1’s manufacturer property is being accessed by simply adding a dot (.) between the Objects variable name (car1) and the property name (manufacturer) of the value we are seeking.

2. Bracket Notation

Bracket notation uses square brackets. Inside these brackets, you provide the property name to access as a String, as in the following example:

console.log(car1['manufacturer']);
// Expected output: Toyota

Unlike dot notation, which refers to the property name like a variable, here we pass the name as a String. The real power behind using bracket notation, though, is that you can provide a computed value that can be used to access the object’s properties.

const carColor = 'color';
console.log(car1[carColor]);
// Expected output: blue

In the example above, we pass a variable (carColor) to the brackets instead of a String.

This notation also proves useful when we want to access a property whose name consists of a multiple-word String.

const user = {
    'eye color': 'brown'
};
console.log(user['eye color']);
// Expected output: brown

Note: To use a multiple-word String as a property name, it must be wrapped in either single or double quotes.

It is not possible to access properties with multiple-word names using dot notation. As such, it’s advisable to avoid the use of properties with multiple-word strings as their name – instead, you should name these properties using camelCase.

Add or Update an Object property

Adding (creating) or updating (modifying) an Object’s property is pretty simple.

To update a property’s value, simply access the property using either dot or bracket notation and assign it a new value:

car1.color = 'white';
console.log(car1); // Expected output: {
// color: "white"
// go: ƒ drive(location)
// manufacturer: "Toyota"
// mileage: 14638
// model: "Yaris"
// year: 2019
// }

As you can see in the example above, the only value that was changed is that of the color property. Yet, the order of the properties has changed as well. Unlike Arrays, which are a special kind of Object, Object properties are not ordered hierarchically by index.

If we provide the name of a property that doesn’t already exist on the object, a new property is created on the object as we can see below:

car1.spareTire = true;
console.log(car1); // Expected output: {
// color: "white"
// go: ƒ drive(location)
// manufacturer: "Toyota"
// mileage: 14638
// model: "Yaris"
// spareTire: true
// year: 2019
// }

In the above example, the original definition of const car1 did not include a property called spareTire. Thus, when we accessed the spareTire property, it was created on the object. Furthermore, all of the other properties retained their value (the color property was changed in the previous example).

Note: if you intend to update a property but make a mistake while typing the name, you might end up creating a new property on the Object!

Deleting a property

If you wish to remove a certain property from an Object, you can use the delete operator. The delete operator uses the following syntax:

delete objectName.propertyName

The code below demonstrates this syntax by deleting a property from car1:

delete car1.spareTire;
console.log(car1); // Expected output: {
// color: "white"
// go: ƒ drive(location)
// manufacturer: "Toyota"
// mileage: 14638
// model: "Yaris"
// year: 2019
// }

In the example above the spareTire property is removed from the Object car1 using the delete operator. The rest of the Object’s properties remained unchanged – only spareTire is removed.

Note: if you apply the delete operator to the whole object (e.g. delete car1) nothing will happen! If you are using strict mode, you will be notified of an Uncaught SyntaxError when doing so. Otherwise, when not using strict mode, the Object will simply remain unchanged and the code will continue running.

delete car1;
console.log('car1: ', car1); 
// Expected output: Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.

Deleting all properties of an Object

To delete all properties of an object, assign an empty object ({ }) to the object’s name, as we see below:

car1 = {};

However, we quickly run into an issue when deleting car1’s properties. Because we defined car1 as a constant variable (const), we are not allowed to delete all of the properties of this object. The code above will return Uncaught TypeError: Assignment to constant variable. To avoid receiving this error, either use a let variable to define the object or use a for…in loop to iterate over the Object and delete each property individually.

Invoking Object methods

To invoke an Object’s method, simply access the property name which holds the method, followed by parentheses and the list of required arguments:

const ny = car1.go('New York');
console.log(ny);
// Expected output: Driving to New York

In the code above, the go method contains the following function:

function drive(location) { return ‘Driving to ‘ + location }

This function accepts one argument, for the location parameter. When invoked, the method returns the string ‘Driving to’ followed by the location argument. In the example above, the result of calling the go() method is ‘Driving to New York’.

Note: If you access the method without providing the parentheses, the function itself is printed to the console and it is not invoked, thus the return value is not provided as a result.

Note: If you wish for a property to be a method on the Object, you must use the function keyword when defining the property. If you do not use the function keyword while defining a method, as we see below, you’ll encounter unexpected behavior:

function ignite() {
    return 'Engine is running... '
}
const car3 = {
    start: ignite()
}

In the above example, the function ignite() is defined outside of the Object car3. Because of this, the start property is not a function, but is instead set as a reference to the return value of the ignite() function.

In this case, the value of the property is accessed without parentheses:

const x = car3.start;
console.log(x);
// Expected output: Engine is running...

Because start is only a reference to the return value of function ignite(), it is not possible to assign arguments as parameters when accessing it. This is because the start property is not a function, due to being created without the function keyword. Simply adding parentheses to the property will result in an error:

const x = car3.start();
console.log(x);
// Expected output: Uncaught TypeError: car3.start is not a function

Note: In order for this code to work properly, ignite() must be defined!

Tip: You can use the for…in statement to iterate over an Object.

 

Related Articles

JavaScript – Data types explained

JavaScript – How to Use JSON.stringify

JavaScript – How to Get an Object’s Keys and Values

Get AI Code Completions for Your IDE