How To Create An Object in JavaScript

What is an Object in javascript?
An Object is a special kind of array that stores data as a {key-value} pair. A single pair of this data is called a property of that object.

Below are some of the ways to create an object in JavaScript;

Object Literal

Using the object literal {}, we can create a simple object that stores a user's name and email address.

const profile = {
name : "Simon",
  email : "me@you.com"
}

Now if we want to retrieve the user's name, I would do something like this

console.log(`${"Hello ", +profile.name}`);

 

Constructor Function

constructor function is a function that is used to create an object.

You just have to declare the function, then make use of this keyword within the function to set the function's properties.

function profile(name, email){
this.name = name;
this.email = email;
}

You can see how I declared the function, then made use of this keyword to define properties that the function will have.

To create an object using a constructor function, you have to create a new instance of that function using new keyword.

const myProfile = new profile("simon", "test@gmail.com");
console.log( `${"My email is "+ myProfile.email}` );

Here's the code on my console

 

Factory Function

A factory function is a function that returns an object. To create a factory function, you must first declare a function, then on your return statement, use the Object literal notation to return the object.

function profile(name, email){
return{
name : name,
email : email
}
};

To use it, invoke it like any other function.

const myProfile = profile("Tony", "test@gmail.com");
console.log("My name is "+myProfile.name);

 

There are other ways to create an object like using the object.create method. But that will lead you to prototypes.

I hope you've learned something new today.

Thank you for reading


Simon Ugorji

16 Blog posts

Comments