Skip to main content

Command Palette

Search for a command to run...

What are Objects in JavaScript?

Updated
•8 min read•View as Markdown
What are Objects in JavaScript?
T

Craftsman

In programming, an object is a collection of key value pairs. It is a self-contained set of related values and functions.

It is similar to real-world objects in the sense that it has properties and methods.

Let's consider a book object. It has properties like "color and pages" and methods like "open and close".

In javascript, these properties can be of any value type ranging from strings, boolean, arrays, numbers and even objects. The methods are functions.

If we were to create this book object in Javascript, it would look like this:

let book = {
  color: 'black',
  pages: 30,
  open: function () {
    console.log('Open the book');
  }
  close: function () {
    console.log('Close the book');
  }                          
}

As we can the in the book object above, the key is to the left-hand side of the colon, while the value is to the right-hand side of the colon.

It also has ** properties** like the color and number of pages and it has methods like open and close.

There are several ways to create an Object in JavaScript, but we'll just be covering three in this article.

  1. Object Literal Syntax

  2. Factory Function Syntax

  3. Constructor Function Syntax

Object Literal Syntax

In object literal syntax, we create a variable using let or const and then on the right hand side, we assign the objects to it. It's syntax is like so:

let object = {
// object properties and methods...
}

A good example of object created using this syntax is the book object we created earlier. Let's create another object using this same syntax

let circle = {
  radius: 1,
  draw: function() {
    console.log('Draw a circle');
  }
}

The circle object above has a property of radius and it also has a method of draw.

While this is a very simple way to define objects, it is not advisable to use it when creating objects that have many methods.

This is because, if we want to duplicate an object, we'll have to copy and paste or rewrite several methods.

To solve this it is better to use the next two methods.

Factory Function Syntax

This uses a function to pre-define the members of an object.

To create an object, we just need to assign the variable and point it to the function . It's syntax is like so:

function objectCreator () {
  // propeties and methods
}

let object = objectCreator();

This will create an object called object and it will have the properties and methods defined within the objectCreator function.

Let's create our circle object using this syntax:

function circleCreator () {
  return {
    radius: 1,
    draw: function () {
      console.log('Draw a circle')
    }
  }
}

let circle = circleCreator();

This is an identical circle object with the one we created earlier. It has a property of radius and a method of draw.

Now let's move to the third syntax.

Constructor Function Syntax

This is quite similar to the Factory Function syntax.

The only difference is in the naming convention and the keyword used.

The Factory function syntax uses the return keyword while the Constructor function syntax uses the this keyword.

Also when naming a Constructor function, the first letter is capitalized. Let's look at the syntax below

function Object () {
 // properties and methods assigned using the `this` keyword
}

let object = new Object()

the this keyword refers to the object that it is within. While the new keyword creates a new object and points the variable to it.

It also defines the scope of the this keyword and sets it to the newly formed object. Let's create our circle object using this syntax.

function Circle_creator () {
  this.radius = 1
  this.draw = function () {
    console.log('Draw a circle');
  }
}

let circle = new Circle_creator()

In the example above, the new keyword creates an empty object and then defines the scope of the this keyword in the Circle_creator function.

That means thethis keyword is now a reference to the newly created object.

All the properties and method declared using the this keyword is now transferred to the newly created object which we then name circle.

I hope you understood this concept.

Every Data Type in JavaScript is an object. This statement might sound odd but it is in fact true.

This is because anytime we initialize a new variable in Javascript, under the hood or behind the scenes, Javascript uses the constructor function Syntax to make or create the variables.

How to Access the Members of an Object

Viewing the members of an Object

We can view the members of an object using the dot notation or the square brackets notation.

Let's view members of our circle object.

// Using the Dot notation
circle.radius // this will give us 1
circle.draw() // this will return the content of the function 

// Using the square bracket notation
circle["radius"] // this will give us 1

// We cannot use the square bracket notation to access the methods of an Object.

Now why do we even use the sqaure bracket notation?

We use it when we want to access properties of an object when the name or key of that property is not a valid-identifier.

This means when they include spaces our special characters.

Imagine if our Object had a property named "location point" or "location_point".

To access it, we can only use the square bracket notation like so.

circle["location point"] 
//or
circle["location_point"]

When using the square bracket notation, we must place the name of the properties inside a quotation mark.

How to Change Members of an Object

In Javascript, all objects are mutable. That is new properties can be added to them, it's properties can be updated and even deleted.

To change the members of an object, we assess it using the dot or square notation and then set it's values.

Let's say we want to change the value of our radius property in our circle object, we can do that like this

circle.radius = 2 
// or
circle["radius"] = 2

This accesses the radius property and then changes its value to '2'.

How to Add Members to an object.

To add members to an object, we use the same concept of changing the members of an object.

We do this by setting a unique name and assigning a value to it.

Let's create a new property named and add it to our circle object. We do it like this.

circle.diameter = "17m"
// This creates a circle called diameter and assisngs tbe value of 17m to it.

How to Delete Members from an Object.

To delete members from an object, we use the delete keyword.

If we want to delete the diameter property from our circle object. We do it this way

delete circle.diameter
// This deletes the diameter property.

At this point I will have to introduce you to a concept peculiar to the Construtor Function syntax called Closures.

What is Closure?

A closure is the idea of determining what variables will be accessible by an inner function. Let's look at the constructor function below:

function Circle () {
 this.radius= 1
 let defaultRadius= 4
 let computeLocation= function () {
  console.log('Draw a circle'):
 }
 this.draw= function () {
  computeLocation();
  console.log('We drew a circle');
 }
}

From the example above, the properties declared using the this keyword are within the scope and closure of the Circle function.

While the properties declared using the let keyword are within scope of the Circle function but within the closure of an inner function, in this case the draw function.

This means that if we want to place a property within the closure of an inner function, we use the let or const keyword.

This technique is particularly important in Object oriented programming where we deal with concepts like Abstraction.

Private Members

Private members are members of a constructor function that is within its scope but within the closure of an inner function.

We are only accessible inside and inner function but cannot be accessed outside the parent function.

In our example above the computeLocation is a private member.

Public members

Public members are members of a constructor function that is within its scope and also within its closure.

These members are accessible within and outside the constructor function.

Getters, Setters and the Object.defineProperty

The Object.defineProperty is used to access the properties of a private member in a constructor function. It has three arguments which are:

  1. The object we want to to access it's properties.

  2. The name of the property we want to access.

  3. The getter and setter property which is an object that has a key value pair. The key being the get or set keyword and the value being a function.

Let's visualize this using this example.

Object.defineProperty(this, 'defaultRadius', {
 get: function () {
  return defaultRadius 
 }
 set: function (value) {
  defaultRadius = value
}
});

// Now we can access the private property of the Object like so

console.log(circle.defaultRadius) // This will return the value of 4 which is the original value.
circle.defaultRadius = 3 // This sets the value of the defaultRadius property and if we console.log it it'll return 3.

The get keyword is used to only access the values of a private property while the set keyword can be used to alter its value.

And that's a wrap, as we have seen, objects are the most important data type in JavaScript and they form the building blocks of modern JavaScript.

If you have any suggestions or questions, do well to indicate in the comments section.

More from this blog

Tonie

16 posts