Objects

Objects are a fundamental part of JavaScript, providing a way to group related data and functions. In this section, we’ll explore JavaScript objects, which allow you to create structured data models and encapsulate functionality. Understanding objects is key to mastering JavaScript, as they form the backbone of most JavaScript applications.

Desired Outcomes:

  • Learn what objects are in JavaScript and how they are used to store collections of data and more complex entities.
  • Understand how to create objects, access their properties, and modify them.
  • Learn how to add methods to objects and how this keyword works in the context of an object.
  • Explore object constructors and prototypes for creating object templates.
  • Understand the prototype chain and how inheritance works in JavaScript objects.
  • Familiarize yourself with built-in object methods and properties.

Object-oriented programming is an essential part of JavaScript. When you open a web page with a browser, a series of JavaScript objects are created with properties and capabilities based on HTML and other parts of the loaded document content. These objects are hierarchically connected according to the structure of the HTML document. Such a structure is called the DOM (Document Object Model), which will be discussed in detail in the next chapter. Each JavaScript object has its properties associated with it.

You've already learned that JavaScript variables are containers for specific data. Objects are also variables, but objects can contain multiple values in so-called key-value pairs.

Objects are most often written with a capital initial letter (Pascal-case), and the syntax for writing objects is as follows:

var ObjectName = {
    key1: "value1",
    key2: "value2",
    keyN: "valueN"   
};

Creating and Accessing Properties

Key/value pairs are called object properties and are separated by commas. If we take the example of a Person object, the properties of the object could look like this:

var Person = {
    firstName: "John",
    lastName: "Doe",
    birthYear: 1978    
};

The Person in the above example is an object with properties firstName, lastName, and birthYear. These properties are accessed using dot notation (person.firstName) or bracket notation (person["lastName"]).

To access a specific property within an object, you can do it as follows:

ObjectName.propertyName;

If you wanted to access the firstName property from the Person object example, you would do it in one of two ways:

Person.firstName;
Person["lastName"];

Functions in Objects

It is also possible to write functions as properties of an object. Object functions are known as object methods. In the example below, the Person object is extended with a method for returning the full name.

var Person = {
    firstName: "John",
    lastName: "Doe",
    birthYear: 1978,
    fullName: function() {
      return this.firstName + " " + this.lastName;
    }
}

To call the fullName function, you can do it as follows.

Person.fullName();
var fullName = Person.fullName();

If you leave out the parentheses “()” when calling the function, the function definition will be returned.

Iterating Over Object Properties

You can loop through each key-value pair in an object using a for...in loop. We will discuss loops in the next lessons.

for (let key in person) {
    if (person.hasOwnProperty(key)) {
        console.log(key + ": " + person[key]);
    }
}  


The for...in loop iterates over each property in the person object, printing the property name and its value.

Nested Objects

Objects can contain other objects, enabling the construction of complex data structures.

let person = {
 name: {
  first: "John",
  last: "Doe"
 },
 age: 30
};

console.log(person.name.first); // "John"

The person has a name object as a property, which in turn has first and last properties.

Object Inheritance

JavaScript objects are prototypical, meaning they can inherit properties and methods from other objects.

let employee = Object.create(person);
employee.job = "Developer";
console.log(employee.job); // "Developer"
console.log(employee.name.first); // "John" - inherited from person

The employee object is created as a new object that inherits from person. It has its own property job, and also access to properties of person.

Object Constructors

A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

What is this?

In JavaScript, the this keyword refers to an object. Which object it refers to depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

  • In an object method, this refers to the object.
  • Alone, this refers to the global object.
  • In a function, this refers to the global object.
  • In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.

Working with objects

In the following example, the user is asked to enter the name and surname of a person. The Person is created as an object that contains properties; name, surname, and a function that returns the full name. When the user enters the name and surname, the Person object is filled and the values are displayed using the alert(); function.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>JS - Working with objects</title>
    <script>
        function Person(name, surname) {
            this.name = name;
            this.surname = surname;
            this.fullName = function () {
              return this.name + " " + this.surname;
            }
        }

        function runApp() {
			// Regular binding to properties
            var p = new Person();
            p.name = prompt("Enter the person's name:", "");
            p.surname = prompt("Enter the person's surname:", "");
           //   Using the constructor
           //   var person = new Person(
           //     prompt("Enter the person's first name:", ""),
           //     prompt("Enter the person's last name:", ""));

            alert("Entered person: " + p.fullName());
        }
    </script>
</head>
<body>
    <h1>JS Work with objects</h1>
    <a href="#" onclick="runApp()">RUN APP</a>
</body>
</html>

Updated on:

Part of our complete: JavaScript Fundamentals guide

Want exercises and real projects for this lesson? Get the full course.