Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Create Objects in JavaScript

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.

How to Create Objects in JavaScript

There are several different ways to create new objects in Javascript

  1. Using Object Literal
  2. Using a new keyword with a constructor function
  3. Object.create method
  4. Object.assign() method
  5. 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

  1. Enclose everything in a curly bracket
  2. Use colon as a separator between a property name (key) and its value
  3. Use a comma as a separator between each key-value pair
  4. Comma at the end of the last key-value pair is ok.
        
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.

        
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.

        
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.

        
let str = new String();    // String Object
let num = new Number();    // Number object
let bool = new Boolean();  // Boolean object
  
    
        
    

Creating an new Array

                                
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

  1. Create a Regular JavaScript Function
  2. Assign all the properties & methods to the object pointed by this
  3. Invoke it with new keyword
                            
//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.

                            
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.

                            
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

        
 var src1 = { a: 10 };
var obj = Object.assign({}, src1);
 
console.log(obj )
 
    
        
    

Creating a new object from Multiple Sources.

        
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.

        
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.

                        
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                                 
                                

Refer to Getters & Setters in JavaScript for more on accessor properties

Object Methods

Methods are like verbs. They perform actions.

Unlike the programming languages like C# & Java, Javascript allows us to store the function in a variable and use it later.

When we assign a function to a property, we call that property a method.

In the following example, we assign a function to the Property fullName


let person = {
  firstName: "Allie",
  lastName: "Grater",
  age: 50,
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};  
            
        

Read More

  1. JavaScript Tutorial
  2. Functions in JavaScript
  3. Function Arguments & Parameters
  4. Default Parameters
  5. Pass By Value & Pass By Reference
  6. Function Expression
  7. Nested Functions
  8. Immediately-invoked Function Expressions (IIFE)
  9. Callback functions
  10. Arrow functions
  11. Arguments Object
  12. Rest Parameters