JavaScript Object and multiple ways to create it

In JavaScript, objects are king.

What is 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

JavaScript defines 5 types of primitive data types:

  • string
  • number
  • boolean
  • null
  • undefined

Object Creation

1. Using the Object() constructor:

let obj = new Object();

2. Using Object.create() method:

let obj = Object.create(null);

3. Using the bracket’s syntactig sugar:

let obj = {};

4. Using a function constructor:

let ObjCreate = function(name) {
this.name = name
}
let obj = new ObjCreate("abhayjain13");
function f {};

new f(a, b, c);

Would be equivalent to:

// Create a new instance using f's prototype.
let newInstance = Object.create(f.prototype)
let result;

// Call the function
result = f.call(newInstance, a, b, c),

// If the result is a non-null object, use it, otherwise use the new instance.
result && typeof result === 'object' ? result : newInstance

5. Using the function constructor + prototype:

function myObj(){};
myObj.prototype.name = "abhayjain13";
let obj = new myObj();

6. Using ES6 class syntax:

class myObject  {
constructor(name) {
this.name = name;
}
}
let obj = new myObject("abhayjain13");

7. Singleton pattern:

let obj = new function(){
this.name = "abhayjain13";
}

--

--

Developer with 3 yrs of industrial experience in developing scalable web applications.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.