DEV Community

loading...

Three ways to create an object in JavaScript

barriosdfreddy profile image Barrios Freddy Updated on ・1 min read

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

Discussion (4)

pic
Editor guide
Collapse
Sloan, the sloth mascot
Comment deleted
Collapse
barriosdfreddy profile image
Barrios Freddy Author

You're right, thank you!

Collapse
alimrandev profile image
Abdullah Al Imran • Edited

class Person {
constructor(name){
this.name = name
};
sayHello(){
return Hi ${this.name}
}
}
const person = new Person('Jon Doe');

console.log(person.sayHello()); //HI Jon Doe

You can also use the constructor function to create an object in es6.

Collapse
barriosdfreddy profile image
Barrios Freddy Author

Yeah... that's it, thank you