Skip to content

Objects

Objects in JavaScript are references that store information where the object properties are stored. These properties are pairs, consisting of key and value. The value for a certain key can be any type, i.e. it can be a primitive value, a reference value (e.g. a list or another object) or a function (the so-called object method).

Creating objects

We can create objects in JavaScript in several different ways. The easiest way is to define an object by directly using a letter, i.e., inside the { and } brackets. Individual keys and values are separated from each other by a : character, while individual pairs are separated by a ,. The following example creates an object in this way:

const person = {
    firstName: 'John', // property of type string
    lastName: 'Smith',
    'middleName': 'Adam', // the key can be saved as a string
    grades: [4, 6, 5], // property being an array
    job: { // property being an object
      position: 'Software Developer',
      mainLanguage: 'Not JavaScript'
    },
    describeJob: function() { // the function is also an object property (the so-called method)
      console.log(`${this.firstName} has job ${this.job.position} and main language is ${this.job.mainLanguage}`);
    },
    welcome: () => console.log('hi ' + this.firstName) // the arrow function can also be an object property
};

Access to the value

In order to gain access to a certain property in the object we can use:

  • the dotted notation,
  • the bracketed notation.

To access the fields of the person object defined in the previous example, we can use the following code:

console.log(person.firstName); // John / a dotted notation was used
console.log(person['lastName']); // Smith / a bracketed notation was used
console.log(person.middleName); // Adam
person.describeJob(); // calling the method on the object
person.welcome(); // hi undefined 

Arrow functions do NOT provide bindings with this.

In JS, we often build objects using the so-called factory function:

function createAnimal(name) {
    return {
        name, // the abbreviated notation explained below
        type: `dog`
    }
}

const animal = createAnimal('Kitty');
console.log(animal); // will be displayed {name: "Kitty",type: "dog"}

The above example, when creating an object in the createAnimal function, uses a shortcut for the name property. By providing only one argument (instead of a key and value), its name becomes a key.

Other ways to create objects

In JavaScript, each object is created using the built-in object called... Object. An object can be created using the new operator, e.g:

const person = new Object(); // alternative for { }
person.firstName = "John";
person.lastName = "Doe";

console.log(person); // {firstName:"John",lastName:"Doe"} will be displayed

The example above shows that we are able to add more properties to a once created object (and we are also able to remove them).

We can also create an object with the help of the so called function constructor. This is nothing but a function created using the keyword function and by convention it starts with a capital letter (like a Java object). Such an object may have properties that you create by using this reference. Such an object is created with the new operator, e.g:

function Person(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.describe = () => console.log(`${this.firstName} ${this.lastName} has age ${this.age}`);
}

const person = new Person("John", "Doe", 7);
person.describe();

Objects can also be defined with the keyword class. This word does NOT mean that our object becomes a special object and does NOT introduce new mechanisms (e.g. object-oriented inheritance model). This is only a clearer way to define objects.

  • constructor in an object defined with class, we define with the keyword constructor.
  • we can create getters for properties using the keyword get, setters using set.
  • it is possible to create static methods using the keyword static. Static methods do not require an object instance in order to use them.

The next example shows how to define an object with a class:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.allGrades = [];
  }

  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  set grades(grade) {
    this.allGrades.push(grade);
  }

  getWelcomeMessage = () => `Hello ${this.firstName}`;
}

const person = new Person('Andrew', 'Williams'); // creating an object defined with class
console.log(person.getWelcomeMessage()); // Hello Andrew
console.log(person.fullName); // Andrew Williams
person.grades = 5;
person.grades = 6;
console.log(person.allGrades); // [5,6]