A Beginner's Guide to Objects in JavaScript

An object, for example, a pen, has characteristics and actions. A pen has characteristics such as color, brand and ink. A pen can perform actions such as writing. Similarly, objects are collections of functions and variables.

In this article, you'll understand how to create and use objects.

What are Objects?

Objects are collections of data and the functions that use them. The data that is stored in an object is called a property while the functions are called methods.

You have already interacted with objects in JavaScript and here are a few examples:

// declaring a string
let str = "Hey!"
// declaring an array
let arr = []

// example of a property
str.length // 4

// example of a method
arr.push("one")

Objects are also defined as key-value pairs. The key is the name used to access the property or method while the value is the value of the property or method.

The syntax of an object is

const object = {
    key1: value1,
    key2: value2,
    key3: value3
}

An object is enclosed in curly braces({}). The key and value are separated by a colon(:) and the key-value pairs are separated using a comma(,).

How to Create Objects in JavaScript

There are 3 different ways to create objects.

Using an Object literal

An object literal uses curly braces({}) to create an object. For example,

const firstObject = {}

We can add properties and methods using the dot notation or the bracket notation. Let's create an Employee object.

const employee = {}

// adding properties
// using dot notation
employee.name = "Anna Marie"
employee.department = "IT"
// using bracket notation
employee["deparment role"] = "Senior Software Engineer"

//adding methods
// using dot notation
employee.checkIn = function(){
    console.log("PRESENTTTT!!!!!")
}
// using bracket notation
employee["join meeting"] = function(){
    console.log(employee.name + "joined the meeting")
}

console.log(employee)
/*
{
name: "Anna Marie",
department: "IT",
"deparment role": "Senior Software Engineer",
checkIn: function(){
    console.log("PRESENTTTT!!!!!")
},
"join meeting": function(){
    console.log(employee.name + "joined the meeting")
}
}
*/

The bracket notation is not commonly used unless:

  1. the property name has a space

  2. the property name has special characters

This is a great way to create objects but it has a few limitations such as,

  • if you need to create a similar object, you will have to repeat the code

  • the properties and methods are added after the object is declared making the code hard to read

To solve these limitations, we can use a factory function to create objects.

Using a factory function

A factory function is a function that creates an object and returns it. The function can be used to create multiple objects that have similar properties and methods.

Let's create a factory function that creates employees.

function createEmployee(name, role, department){     
    // create the object     
    let employeeObj = {}     
    // add properties    
    employeeObj.name = name     
    employeeObj.role = role     
    employeeObj.department = department      

    // add methods     
    employeeObj.checkIn = function(){         
        console.log("PRESENTTTT!!!!!");    
    }          
    employeeObj["join meeting"] = function(){         
        console.log(this.name + "joined the meeting");     
    }      
    return employeeObj 

}  

let anna = createEmployee("Anna Marie", "Senior Software Engineer", "IT")

The example above enables you to create multiple employees.

The this keyword is used to reference the current object. In the employeeObj["join meeting"] method, the this keyword is used to reference the object that is currently being created.

The limitation of the factory function is creating, initializing and returning an object.

Alternatively, you can create a constructor. A constructor is a function that creates and returns an object. Constructors always start with a capital letter. The this keyword is used to create properties and methods.

The new keyword is used to create an object instance.

 function Employee(name, role, department){
    this.name = name
    this.role = role
    this.department = department

    this.checkIn = function(){
        console.log("PRESENTTTT!!!!!")
    }

    this["join meeting"] = function(){
        console.log(this.name + "joined the meeting")
    }
}

let anna = new Employee("Anna Marie", "Senior Software Engineer", "IT")

Objects give us a great way to organize our code by implementing Object Oriented Programming. Constructors are a great way to create objects as they prevent code duplication. However, JavaScript has features that make it easier to implement Object Oriented Programming concepts.

To create objects that can easily use Object Oriented Programming concepts, we can use classes.

Using a Class

Classes are used to create objects and they make your code readable. Classes can only contain methods. Therefore we need to use a constructor method to store the object's properties.

 class Employee{
    constructor (name, role, department){
        this.name = name
        this.role = role
        this.department = department
    }

    checkIn(){
        console.log("PRESENTTTT!!!!!")
    }

    joinMeeting(){
        console.log(this.name + "joined the meeting")
    }
}

let anna = new Employee("Anna Marie", "Senior Software Engineer", "IT")

Methods declared in a class do not have a function keyword.

Classes allow you to inherit properties and methods and create sub-classes. Let's create a sub-class.

 class Employee{
    constructor (name, role, department){
        this.name = name
        this.role = role
        this.department = department
    }

    checkIn(){
        console.log("PRESENTTTT!!!!!")
    }

    joinMeeting(){
        console.log(this.name + "joined the meeting")
    }
}

let anna = new Employee("Anna Marie", "Senior Software Engineer", "IT")

class Contractor extends Employee {
    constructor(name, role, department, contractTime, paySchedule){
        super(name, role, department)
        this.contractTime = contractTime
        this.paySchedule = paySchedule
    }
}

let moses = new Contractor("Moses", "Web Developer", "IT", "6 months", "weekly")

The extends keyword allows you to inherit properties and methods from another class. The super keyword creates inherited properties.

Inheritance prevents code duplication and is a great Object Oriented Programming concept. To get a better understanding of inheritance, you can check out my article that covers Object Oriented Programming concepts.

Summary

  • Objects are collections of characteristics and actions. They store data and functions.

  • Objects are collections of key-value pairs.

  • Properties are variables that are stored in objects.

  • Methods are functions that are stored in objects.

  • Objects can be created using object literals, factory functions, constructors or classes.

  • You can add properties and methods using dot notation or bracket notations.

  • Constructors are functions that create and return objects.

  • Constructors start with a capital letter.

  • The new keyword is used to create a new object using a constructor or class.

  • The this keyword is used to reference the current object.

  • The super keyword creates properties based on the parent class.

  • The extends keyword allows you to inherit properties and methods from another class.

0
Subscribe to my newsletter

Read articles from Michelle Ndiangui directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Michelle Ndiangui
Michelle Ndiangui

Hey, I'm Michelle. I'm a Kenyan Computer Science student who is committing to becoming a software engineer by the end of the year 2023.