Creating Object in Javascript — 4 Ways
Creation of object in JS using
- Object.create
- Object literal
- Constructor Function
- ES6 Class
Using Object.create
- Raw kind of creation.
- Any other type of object creation(which are syntactic sugar) would essentially under the hood, use this type of creation only.
- Example —
This will create object like
Want simpler way of creation? See next type 😎.
Using object literal
- Syntactic sugar to Object.create
- Most frequently used type, as its very easy
- Can easily add and remove new properties to object.
- Example —
Here we have created two objects.
We can add new function property to vanillaCake object like this —
vanillaCake.addCherry = function() { this.isCherryAdded = true; }
Note that this won’t be added to chocolate cake object. You can verify as
console.log(chocolateCake.addCherry); // returns undefined
How can we add it to all cake objects 🤔? We have to add it to prototype. See next type of creation 😎.
Using Constructor Function
- Provides a template kind of creation
- new keyword to create object
- For those who come from object oriented programming world, might have following concerns,
in above 2 types —
- Nowhere we defined shape of cake i.e. what all properties cake can have.
- No way to define that vanillaCake and chocolateCake are type of Cake.
- How to add new property only to all cake objects?
This type is just syntactic sugar added to object.Create, to solve above concerns easily and make our life easy 😌.
- Now, we have Cake function, which adds properties to this object. So we have way to define shape of cake object.
- We can find if vanillaCake object is of type Cake using
console.log(vanillaCake instanceof Cake); //returns true
3. Add new property to all Cake objects by simply adding it to prototype object as shown in above code snippet. Now we can do
chocolateCake.addCherry();
console.log(chocolateCake.isCherryAdded); //returns true
Still not satisfied? Want in more object oriented way 😜? See next type 😎.
ES6 Class
- Even more syntactic sugar
- Like a traditional way of creating classes and objects.
- Easy to use and understand
- Object oriented programmers ( include me 😅) now may feel relaxed by having this kind of syntactic sugar 😉.
Btw I learned these 4 ways of creating objects in JS. There might be other ways, which essentially might be different flavours of above types. If still there are any other ways that you are aware of and I missed it, I would be happy to know, as like you even I am also learner 😄