In this tutorial, we will see how to Create Objects in JavaScript. Objects provide a way to group several values into a single value. The object internally uses a collection of key-value pairs to store values. JavaScript has several ways by which you can create an object. Let us explore that in detail.
Table of Contents
How to Create Objects in JavaScript
There are several different ways to create new objects in Javascript
- Using Object Literal
- Using a
new
keyword with a constructor function Object.create
methodObject.assign()
method- Using ES6 Class Statement
Using Object Literal
An object literal in JavaScript allows us to create plain JavaScript objects. It consists of a list of key-value pairs, each separated by a comma and wrapped inside curly braces.
To create a object using object literal syntax
- Enclose everything in a curly bracket
- Use colon as a separator between a property name (key) and its value
- Use a comma as a separator between each key-value pair
- Comma at the end of the last key-value pair is ok.
1 2 3 4 5 6 7 8 9 10 11 12 13 | var person = { firstName: "Allie", //FirstName Property lastName: "Grater", //lastName Property age: 50, //age getName : function () { console.log(this.firstName + ' ' + this.lastName) } }; person.getName(); //Allie Grater |
You can read more about Object Literal in JavaScript.
Using a new keyword & Constructor function
JavaScript object Constructor function allows us to create multiple similar objects easily. We invoke the constructor function using the new operator.
The constructor function is a regular JavaScript function that contains a recipe to create a new object. When we invoke it using the new operator it creates a new instance of the object and returns it.
Built-in Constructor Function
JavaScript provides some built-in constructor functions. One of them is the Object
constructor function. The return value of the Object() constructor a new object. Once we create a new create new object, we assign properties and methods to it.
1 2 3 4 5 6 7 8 9 10 11 12 | const person = new Object(); person.firstName = 'Alex'; person.lastName = 'Ferguson'; person.getName = function () { console.log(this.firstName + ' ' + this.lastName) } person.getName(); //Alex Ferguson |
If you pass an object as the first argument to it, It will return it as it is.
1 2 3 4 5 6 7 8 9 10 11 | const person = new Object ( { firstName : 'Alex', lastName: 'Ferguson', getName: function() { console.log(this.firstName+' '+this.lastName); } }); person.getName() //Alex Ferguson |
Apart from JavaScript also have several built-in constructor functions like Function, boolean, Number, BigInt, Math, Date, etc. You can refer to the Complete list of built-in objects in JavaScript.
1 2 3 4 5 | let str = new String(); // String Object let num = new Number(); // Number object let bool = new Boolean(); // Boolean object |
Creating an new Array
1 2 3 4 5 6 7 8 9 10 | let fruits = new Array(); // new Array object fruits.push('Apple', 'Banana') console.log(fruits) //["Apple", "Banana"] //is same as fruits =["Apple", "Banana"] |
User-Defined Constructor functions
Apart from the built-in constructor functions, we can define our own constructor function. To Create constructor function
- Create a Regular JavaScript Function
- Assign all the properties & methods to the object pointed by
this
- Invoke it with new keyword
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //Constructor function function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.fullName = function() { return this.firstName + ' ' + this.lastName; }; } //Create a as many objects as you want let alex = new Person('Alex', 'Ferguson', 50); let santi = new Person('Santi', 'Argo', 40); let sarah = new Person('Sarah', 'Moanees', 25); |
You can refer to Constructor Function & New Operator in JavaScript
Object.create method
The Object.create()
is useful, when you want to create a new object and also want to set an existing object as its Prototype. We pass the Prototype as the first argument to the Object.create() method.
The following code creates a new object alex and sets person as its prototype.
1 2 3 4 5 6 7 8 9 10 11 12 13 | const person = { fullName: function() { console.log(this.firstName+' '+this.lastName); } }; const alex = Object.create(person); alex.firstName = 'Alex'; alex.lastName = 'Ferguson'; alex.fullName() //Alex Ferguson |
The Second argument to object.create
is a property descriptors.
1 2 3 4 5 6 7 8 9 10 11 12 | const person = { fullName: function() { console.log(this.firstName+' '+this.lastName); } }; descriptors= { firstName: { value: 'Alex' }, lastName: { value:'Ferguson' }} const alex = Object.create(person, descriptors); alex.fullName() |
Object.assign() method
Use Object.assign()
method to create a clone of another object (Source). But remember that it only copies its own properties which are enumerable from the Source object
The Object.assign()
also allows copying from more than one source. Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources’ properties overwrite earlier ones.
The following example, creates a new object from Object.assign
1 2 3 4 5 6 | var src1 = { a: 10 }; var obj = Object.assign({}, src1); console.log(obj ) |
Creating a new object from Multiple Sources.
1 2 3 4 5 6 7 8 | var src1 = { a: 10 }; var src2 = { b: 20 }; var src3 = { a: 1, c:30 }; var obj = Object.assign({}, src1,src2,src3); console.log(obj ) //{a: 1, b: 20, c: 30} |
Target is an existing object.
1 2 3 4 5 6 7 8 9 | var obj = { a:1,b:2,c:3,d:4} var src1 = { a: 10 }; var src2 = { b: 20 }; var obj = Object.assign(obj, src1,src2); console.log(obj ) //{a: 10, b: 20, c: 3, d: 4} |
Using Class Statement
Classes in JavaScript were introduced with ES6. They are nothing but Syntactic sugar for the new and constructor function.
The following example shows you how to create a class in JavaScript. We can then use the new keyword to objects from the class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } // Method getName() { return this.firstName +' '+ this.lastName; } } const person = new Person('Alex', 'Ferguson'); console.log(person.getName()); // Alex Ferguson |
Read More