I have used both. But still I couldn't understand clearly. I have read many blogs about that , what I have understood is we can use the constructor function by using new keyword (creating instance). While in the Object literal case we don't need that. Using Object literal is like singleton. I don't know whether I am correct or not. Please let me clear with these two things. When to use?
There is great number of differences between object literals and functions as constructors.
You can have only one instance of object literal, while using function as a constructor you can have as much as you want.
You don't have a constructor when using object literals, so if you want to initialize your object you probably want to have some function in object literal that will initialize your object (init, boostrap etc.).
Object literal's type is Object, while function as constructor is Function, which means that they have different Prototype object linked on first step in prototype chain (Function.prototype will point to Object.prototype).
For every function that you create, there is a new object created called Prototype and function is linked to it with prototype property, while when using object literal you don't get that unique prototype object, it's connected directly to Object.prototype.
For usage purposes, I personally use object literals when I want to have only one instance of that object. Good example is config object (you shouldn't have more config objects in your app). The simplest way to create singleton pattern in JavaScript is using object literals. On the other hand, I would use function as constructor if I need multiple instances of one function. Good example are domain object (User, Task etc.).
Hope that this helps a bit.
This is how I understand it (not necessarily confident that I'm right):
new keyword is somewhat of a syntactical sugar that implements a constructor function under the hood (pretty sure, but could be wrong).Danijel Maksimovic
Senior Fullstack Developer @NearForm
Adam Bene
Founder & CTO @ Bene Studio | Join us!
There are pretty good docs on MDN about this topic: