Three ways to create an object in JavaScript

barriosdfreddy

Barrios Freddy

Posted on November 11, 2020

Three ways to create an object in JavaScript

In JavaScript, there are three ways to create your own objects. Taking into account that almost everything in JS It’s an object.

Object literals

The simplest way to create an object in JS it’s through curly brackets { }.

Define and create a single object in one statement

const person = {
    name : 'Freddy',
    sayHello() {
        return `Hi ${this.name}`
    }
};

console.log(person.sayHello()) // Hi Freddy
Enter fullscreen mode Exit fullscreen mode

New operator

Using the new operator is the same thing as creating objects literally. It’s recommended to use object literals, instead of this, for simplicity and execution speed.

const person = new Object()
person.name = 'Freddy'
person.sayHello = ()  => {
   return `Hi ${this.name}`
}

console.log(person.sayHello()) // Hi Freddy
Enter fullscreen mode Exit fullscreen mode

Also, you can create an object through a constructor function. In this case, the new operator returns an instance of the function, if the function has not an explicit return statement it’ll “this “

function Person (name) {
    this.name = name
    this.sayHello = function() {
        return `Hi ${this.name}`
    }
}
const person = new Person('Freddy')
console.log(person.sayHello()) // Hi Freddy
Enter fullscreen mode Exit fullscreen mode

Object.create() method

In order to define and create a new object through the create
method, we have to use the prototype from another one.

const person = Object.create(Object.prototype)
person.name = 'Freddy'
person.sayHello = function sayHello() {
     return `Hi ${this.name}`
}


console.log(person.sayHello()) // Hi Freddy
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
barriosdfreddy
Barrios Freddy

Posted on November 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Three ways to create an object in JavaScript