Five Different Ways to Create a JavaScript Object

Five Different Ways to Create a JavaScript Object

How to create Javascript object?

·

4 min read

In this article, we will be looking at five different ways to create a JavaScript object. JavaScript is a programming language that is used to make web pages interactive. For example, it can be used to create drop-down menus, animate images, or display data from a database. To create an object in JavaScript, we must first understand what an object is.

What is an Object?

An object is a collection of unordered properties which are in the form of key and value pairs. Properties can usually be accessed using dot notation obj.prop or square bracket notation obj["prop"]. However, there are a few different ways to create them.

1). Object Literal

The most common and simplest way to create a JavaScript object is by using the object literal. Object literal is a comma-separated list of key-value pairs wrapped in curly braces.

Syntax:-

const variable_name = {

key1: value1,

key2: value2,

key3: value3,

}

example:-
    const user ={
            id: 1,
            name: "Raj",
            age: 21,
            gender:"male",
}

We create an object User using object literal and having some properties in curly brackets. The properties are id, name, age, and gender. We access the values of these properties by using dot notation. For example, user.name will return the value of the name property; user.age will return the value of the age property; and so on

2) Creating Object With Object.create() Method

The Object.create() method creates a new object with the specified prototype and properties of the old subject.

syntax:- Object.create(prototype[, properties-object])

const user = {
        id: 1,
        name:"Raj",
        age:21,
        gender:"Male"
}
// create a new object using Object.create
const facebook = Object.create(user)
// add new property in facebook object 
facebook.users = function(){
        console.log(`${this.name} is use facebook`)
        }
//invoke the users method defined in the facebook object
facebook.users();
// output -> Raj is use facebook

The facebook object has access to the user object's attributes. It's been added to facebook prototype chain and this is one way we do inheritance in javascript.

Note:- Every javascript function has a prototype object by default. Method or properties may be attached to his property.

3). Create an object using Constructor Function

A constructor function is just like any other function. When creating an object using the Constructor Function, you need to first create a function that will act as the blueprint for your object. This function will take in any parameters that you want your object to have. Once you have created this function, you can then create new instances of your object by calling the constructor function with the new keyword.

// constructor function
function Person(id,name,age){
    this.id = id
    this.name = name    
    this.age = age
}
const student = new Person(1,"Raj",24)

console.log(student.name)
//output -> Raj
console.log(student.id)
//Output -> 1
console.log(student.age)
//output-> 24

As you can see from the code above, when we use the keyword new with our Person constructor function, it creates an instance of the object and sets the name property to “Raj”. We can then access this property by using dot notation on our student variable student.name. we can add to this not only properties but methods as well.

4). Create an object using Object.assign().

This is another method to create a new object from other objects. The Object.assign() is used to copy the values and properties from one or more source objects to a target object.

const person = {
    id: 1,
    name: "Raj",
    age: 24,
}
//copy properties from person object to student object
const student = Object.assign({}, person)
console.log(student.name)
//Output -> Raj

As you can see from the code above, we create a person object and define attributes like name, age, and id. Then copy all of the attributes to our target object, which is called a student.

5). Create an object using Object.fromEntries()

The Object.fromEntries() accepts an iterable such as Array or Map and transforms it into an Object. This method returns a new object whose properties are given by the entries of the iterable.

Object.fromEntries(iterable);

const person = [
    ['name', 'Raj'],
    ['id', '1'],
    ['age', 21]
];

const student = Object.fromEntries(person);
console.log(student);

//Output -> {firstName: "John", lastName: "Doe", age: 20}

As you can see from the code above, how to convert an array into an object.

Conclusion

In conclusion, there are five different methods for creating JavaScript objects. Depending on your project and the complexity of your code, one or more of these methods will be best suited to achieve your desired results. With that in mind, it is important to understand each option and how it can be used so you can make an informed decision about which method to use for your project.