Skip to content

Objects

Objects in JavaScript are references that store information about where the properties of an object are located in memory. These properties are pairs consisting of a key and values. The value for a certain key can be any type, ie it can be a primitive value, a reference value (e.g. a list or other object), or a function (an object method).

Creating Objects

We can create objects in JavaScript in several different ways. The easiest way is to define the object directly with a literal, that is, inside the { and } braces. Individual keys and values are separated with the : character, and the individual pairs - with ,. The following example creates an object like this:

const person = {
    firstName: 'John', // property of string type
    lastName: 'Smith',
    'middleName': 'Oscar', // the key can be written as a string
    grades: [4, 6, 5], // property being an array
    job: { // property being an object
      position: 'Software Developer',
      mainLanguage: 'Not JavaScript'
    },
    describeJob: function() { // a function is also a property of an object (a 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) // an arrow function can also be a property of an object
};

Access to values

In order to access a certain property in an object, we can use:

  • dot notation,
  • parenthesis 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 / dot notation was used
console.log(person['lastName']); // Smith / the parenthesis notation was used
console.log(person.middleName); // Oscar
person.describeJob(); // calling a method on an object
person.welcome(); // hi undefined 

NOTE: The arrow functions NOT bind to this.

At JS, we often build objects using the so-called factory function, e.g .:

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

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

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

Other ways to create objects

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

const person = new Object(); // alternatywa dla { }
person.firstName = "John";
person.lastName = "Smith";

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

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

The object can also be created using the so-called function builder. This is nothing but a created function with the keyword function and by convention it starts with a capital letter (just like an object in Java). Such an object can have properties that we create using the this reference. We create such an object using 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", "Smith", 7);
person.describe();

We can also define objects using the class keyword. The word NO means that our object becomes a special object and NOT introduces new mechanisms (e.g. object-oriented model of inheritance). It is only a clearer way of defining objects.

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

The next example shows how to define an object with 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', 'Anders'); // creating an object defined with class
console.log(person.getWelcomeMessage()); // Hello Andrew
console.log(person.fullName); // Andrew Anders
person.grades = 5;
person.grades = 6;
console.log(person.allGrades); // [5,6]