How to create an object in JavaScript ?

How to create an object in JavaScript ?

Just like many other other programming languages javascript also supports object oriented design. An object is a data structure which contains the data and the functions to operate on the data and provide meaningful results. The data in the javascript object is stored and retrieved with the help of properties and the methods are the functions which operate on the data to provide certain behavior.

Creating Objects in JavaScript

An object in JavaScript can be created in many ways . Mentioned below are are some of the ways in which we can create an object in JavaScript.

  1. Objects Literal Form :

    Objects in JavaScript can be either written by specifying each of the name value pairs in the objects or it can be initialized as an empty object and then properties or functions are added to it on need basis. This form of creating the JavaScript object is called the Object Literal form.
// creating an empty object
const student = { }
// creating an object with predefined properties and method
const student = {
firstName :  'John',
lastName : 'Doe',
Age : 32,
greeting : function() {
alert('Hello World ! I\'m' + this.firstName + ' . ');
}
  1. Creating an Object with the constructor function in JavaScript

    A constructor function is a function that creates a javascript object instance based on the required parameters passed to
// function definition
function Student(firstName, lastName, Age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.Age = Age;
  this.greeting = function () {
    alert("Hello World ! I'm" + this.firstName + " . ");
  };
}

// invoking the function created above to retrieve an object instance
let student = new Student("John", "Doe", 32);
  1. Creating and object with the Object() Constructor

    We can use the Object constructor of the JavaScript to create a new object and then add properties and method to the newly created object.
let student = new Object();
student.firstName = "John";
student.lastName = "Doe";
student.Age = 32;
student.greeting = function () {
  alert("Hello World ! I'm" + this.firstName + " . ");
};
  1. Creating and object with the create() method

    This method is used to create a new object instance using the previously created object as a prototype for the new instance.
// creating a new object instance student1 based on the prototype of the instance of the student object created in step 3

let student1 = Object.create(student);

I hope that you must have understood the different ways in which we can create objects in JavaScript.

Book Recommendation

I would recommend you to refer to the book JavaScript - The Definitive Guide by David Flanagan for an in-depth understanding of the JavaScript Language.