JavaScript Object and multiple ways to create it
2 min readJan 2, 2021
In JavaScript, objects are king.
What is Object?
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.
JavaScript defines 5 types of primitive data types:
string
number
boolean
null
undefined
Primitive values are immutable
Object Creation
1. Using the Object() constructor:
let obj = new Object();
This is the simplest way to create an empty object.
2. Using Object.create() method:
let obj = Object.create(null);
This method creates a new object extending the prototype object passed as a parameter.
3. Using the bracket’s syntactig sugar:
let obj = {};
This is equivalent to Object.create(null) method, using a null prototype as an argument.
4. Using a function constructor:
let ObjCreate = function(name) {
this.name = name
}
let obj = new ObjCreate("abhayjain13");
What the new operator does is call a function and setting this of function to a fresh new Object, and binding the prototype of that new Object to the function's prototype. As is:
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";
}