DEV Community

Cover image for Different possible ways to create objects in JS
Shish Singh
Shish Singh

Posted on • Edited on

Different possible ways to create objects in JS

In JavaScript, almost "everything" is an object.

Booleans can be objects (if defined with the new keyword)
Numbers can be objects (if defined with the new keyword)
Strings can be objects (if defined with the new keyword)
Dates are always objects
Maths are always objects
Regular expressions are always objects
Arrays are always objects
Functions are always objects
Objects are always objects
All JavaScript values, except primitives, are objects.

Through Object Constructor

const obj= new Object();
Enter fullscreen mode Exit fullscreen mode

This is the simplest way amongst all. This creates and empty object. Currently this approach is not recommended.

Through Object Literal

Also known as object initialiser this is a comma-separated set of name-value pairs wrapped in curly braces.

const obj={
  company:"BMW"
  model:"Z1"
}
Enter fullscreen mode Exit fullscreen mode

Through Function Constructor

Create any function and apply the new operator to create object instances. Function name should be capitalised and not camel case.

function ObjectCreate(gender){
  this.gender=gender;
}

const obj= new ObjectCreate("female");
Enter fullscreen mode Exit fullscreen mode

ES6 Syntax

This is a newest way of creating an object.

class ObjectCreate{
  constructor(companyName){
    this.companyName=companyName;
  }
}

const obj= new ObjectCreate("BMW");
Enter fullscreen mode Exit fullscreen mode

Using Singleton pattern

Singleton is a design pattern that tells us that we can create only one instance of a class and that instance can be accessed globally. This is one of the basic types of design pattern. It makes sure that the class acts as a single source of entry for all the consumer components that want to access this state.

A singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance and this helps in ensuring that they don't accidentally create multiple instances.

const singleObj= new(function SingleObject(){
  this.year = 2016;
})();
Enter fullscreen mode Exit fullscreen mode

Connects

Check out my other blogs:
Travel/Geo Blogs
Subscribe to my channel:
Youtube Channel
Instagram:
Destination Hideout

References

  1. W3S

  2. Freecodecamp

Top comments (4)

Collapse
 
eliabe45 profile image
Eliabe França • Edited

What about JSON.parse("{}") 👀

Collapse
 
shishsingh profile image
Shish Singh

Thanks for commenting...That could also be used...Tried mentioning few amongst many...

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Also Object.create and Object.fromEntries

Collapse
 
shishsingh profile image
Shish Singh

Thanks for commenting...Yes definitely...Tried mentioning few amongst many...