Ways to create objects

Hi, in this post I will show you the ways to create objects in Javascript.

Exist 2 ways to create object one called the literal notation and the other is the object constructor notation.

Literal notation

a) We can create the object first, then the properties and methods are added to it afterwards.

// Literal notation
let hotel = {}; // creating the object 

hotel.name = 'Hotel Cristina'; // property of the hotel object
hotel.rooms = 40; // property of the hotel object
hotel.booked = 25; // property of the hotel object
hotel.checkAvailability = function () { // method of the hotel object
    return this.rooms - this.booked; // "this" will refer to the context of the hotel object
};

console.log('hotel --->', hotel);

Note: look the code (a) and for this way you are going to use “=” instead of “:” to assign the values, and we use “;” instead of “,” between properties.

Result:

b) We can create the object and adding directly the properties and methods

// Literal notation
let hotel = {
    name: 'Hotel Cristina',
    rooms: 40, 
    booked: 25,
    checkAvailability: function () {
        return this.rooms - this.booked;
    }
};

console.log('hotel ---->', hotel);

Note: look the code (b) and for this way you are going to use “:” instead of “=” to assign the values. , and we use “,” instead of “;” between properties.

Result: This way is the most used by developers in general.

Object constructor notation

a) We created the object using the keyword “new” followed of the Object().

// Object constructor notation
let hotel = new Object();

hotel.name = 'Hotel Cristina'; // property of the hotel object
hotel.rooms = 40; // property of the hotel object
hotel.booked = 25; // property of the hotel object
hotel.checkAvailability = function () { // method of the hotel object
    return this.rooms - this.booked; // "this" will refer to the context of the hotel object
};

console.log('hotel --->', hotel);

Result:

b) This way is Object constructor notation too, and we can use a function to create multiple objects. The “this” keyword is used instead of the object name.

// Object constructor notation
function Hotel(nameParameter, roomsParameter, bookedParameter) {
    this.name = nameParameter; // property of the hotel object
    this.rooms = roomsParameter; // property of the hotel object
    this.booked = bookedParameter; // property of the hotel object
    this.checkAvailability = function () {// method of the hotel object
        return this.rooms - this.booked;
    };
}

var cristinaHotel = new Hotel('Hotel Cristina', 40, 25); // Instantiating (creating) a new object from the main "Hotel" object
var nayeliHotel = new Hotel('Hotel Nayeli', 60, 30); // Instantiating (creating) a new object from the main "Hotel" object

console.log('cristinaHotel --->', cristinaHotel);
console.log('nayeliHotel --->', nayeliHotel);

Result: This way is the most used by developers in general.

By Cristina Rojas.