CodeNewbie Community 🌱

Samridhi Vashisht
Samridhi Vashisht

Posted on

Different ways to create objects in JavaScript

JavaScript is a flexible object-oriented language when it comes to syntax. We will see the different ways to instantiate objects in JavaScript.

JavaScript is an object-based language that uses prototypes rather than classes. Before we move forward, let's clarify this. JavaScript allows you to create hierarchies of objects and inherit properties and their values based on this different basis.

  • Creating object with a constructor: Constructor is nothing but a function and with the help of a new keyword, the constructor function allows the creation of multiple objects of the same flavor.
function Person(name) { = name;
  this.age = 21;
var object = new Person("Sudheer");

Enter fullscreen mode Exit fullscreen mode
  • Using object literals: Literals are smaller and simpler ways to define objects. We simply define the property and values inside curly braces.
var object = {
     name: "Samiksha",
     age: 22

Object literal property values can be of any data type, including array, function, and nested object.
Enter fullscreen mode Exit fullscreen mode
  • Creating object with Object.create() method: This method creates a new object by passing the prototype object as a parameter.
var object = Object.create(null);
Enter fullscreen mode Exit fullscreen mode
  • Using Es6 classes: The class feature to create the objects.
class Person {
  constructor(name) { = name;

var object = new Person("Samiksha");
Enter fullscreen mode Exit fullscreen mode
  • Singleton Pattern: Singletons are objects that only exist once. The constructor returns the same instance every time, so one can avoid accidentally creating multiple instances by repeating the call.
var object = new (function () { = "Samiksha";
Enter fullscreen mode Exit fullscreen mode

Top comments (0)