JS Capsules: Objects

JS Capsules: Objects

All JavaScript values are objects, except primitives.

What's an Object?

An object is a collection of properties in key: value pairs.

To understand better, let's take a closer look:

Object Properties

Let us describe a ball using a couple of variables:

let ballSize = 'large';
let ballColor = 'orange';
let ballType = 'basketball';

const ballDescription = `There is a ${ballSize} ${ballType} on the court; its color is ${ballColor}`;

console.log(ballDescription);
// There is a large basketball on the court; its color is orange

The code looks good, but we could make it more concise using an object:

const ball = {size: 'large', color: 'orange', type: 'basketball'}

const ballDescription = `He brought a ${ball.size} ${ball.color} ball to the court; it's a ${ball.type}`;

console.log(ballDescription);
// He brought a large orange ball to the court; it's a basketball

Each key: value pair in the ball object is a property of that object. Properties are like variables, but they're all attached to the same object.

There are two ways to access an object's property:

  • Using dots: object.propertyKey (that's what we used in the example above)
  • Using square brackets: object['propertyKey'] or object[expression].

Object Methods

The value of an object's property can be a function. In this case, it is known as a method. An object method looks like this:

const ball = {
    size: 'large', 
    color: 'orange', 
    type: 'basketball', 
    describeBall: function(){return `There's a ${this.size} ${this.type} on the court, its color is ${this.color}`}
}

console.log(ball.describeBall());
// There's a large basketball on the court, its color is orange

As you must have deduced correctly, describeBall() is a method in the ball object. When accessing an object method, you should put brackets at its end to indicate a function.

this.propertyKey

In our previous example, you must have noticed something like this:

`There's a ${this.size} ${this.type}...`

We didn't create a this variable, so why can we use this in our ball object?

The this keyword is used in an object method to access other properties within the same object. It tells the function to check the object it's currently in, and get the value of a property in that same object.

Creating an Object

There are two major ways to create an object:

  • Using an object literal: const ball = { /* properties */ }; (This is the way we've been doing it so far)
  • Using new Object(): const ball = new Object();


Further Reading