banner



How Many Ways To Create Object In Javascript

After Primitive types in JavaScript, Objects are another type of Variables in JavaScript. And JavaScript is being Object-Oriented with the help of Prototype Inheritance. Hence Objects become the crucial construct of JavaScript.

You can save some time in your application development workflow by knowing some handy ways to create Objects in Javascript. Congratulations on A happy productive day.

All the ways or strategies to create Objects in JS have their specific uses. Of course, you can use them anywhere you want. But keep in mind, it might not serve the purpose of readability or less complexity.

And use these methods with precaution, because:

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.

"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." - Rick Osborne

— Software Wisdom (@SoftwareWisdom) January 14, 2020

Table of Contents:

  • Using Object Notation
  • Object.assign
  • Using Object Spread Operator
  • Object notation with JS Variables
  • Having the value of variable as the key
    • Access key of Object as Array and assign new value
    • Array index access in Object Notation and Object.assign
  • Using Object.create
  • Using a Constructor Function i.e. with new keyword

Using Object Notation

Most simplest way to create an Object in JavaScript is by using the Object Notation.

Enclose the key and value pair in between the curly braces i.e. { }

          const person = {   name: 'Full Name',   email: '[email protected]', };  const employee = {   id: 123456,   person: person, }        

Object.assign

Another way to create objects is by using Object.assign. It will also allow you to create immutable copies of any object.

          const person = Object.assign({   name: 'Full Name',   email: '[email protected]', });  const newPersonDetails = Object.assign({}, person, {   email: '[email protected]' });                  

You can also change the object values with the Object.assign. Like in the following example, we will change the email of the person object with Object.assign

          const person = Object.assign({   name: 'Full Name',   email: '[email protected]', });  Object.assign(person, {   email: '[email protected]' });                  

Using Object Spread Operator

You can use the object spread operator to spread the values of any object into another object.

And hence if the target object is using the object notation, it will create a new one. Let's see in the following example:

          const person = {   name: 'Full Name',   email: '[email protected]', };  const personWithAddress = {   ...person,   address: 'Somewhere on the Earth' };                  

Object notation with JS Variables

With ES6+, you don't need to write the key and then JS variable if the name of both is the same.

For example, if you wanna add the key named website to the person object and you already have a variable named website. You don't need to write them twice.

For example, if you wanna add the key named website to the person object. You can have a variable named website and then you don't need to write them twice in the object as website: website,

          const person = {   name: 'Full Name',   email: '[email protected]', };  const website = 'https://time2hack.com';  const personWithWebsite = {   ...person,   website };                  

Having the value of variable as the key

Sometime you wanna create a key on the existing object, but you don't know the name of the key; it is dynamic. In those cases, there are two ways to create an object with dynamic keys:

Access key of Object as Array and assign new value

As you know, you can access the value in an object in the same way you access the Array value using indexes. You can use the same way to create those keys in the object.

          const person = {   name: 'Full Name',   email: '[email protected]', };  console.log( person.name ) // Full Name console.log( person['name'] ) // Full Name  const fullNameKey = 'name';  console.log( person[fullNameKey] ) // Full Name  const newKey = 'phone'; const phoneNum = '00123456789';  person[newKey] = phoneNum;  console.log(person); // 👆→ { name: ..., email: ..., phone: '00123456789' }                  

Array index access in Object Notation and Object.assign

          const person = {   name: 'Full Name',   email: '[email protected]', }; const newKey = 'phone'; const phoneNum = '00123456789';  Object.assign(person, {   [newKey]: phoneNum, });  console.log(person); // 👆→ { name: ..., email: ..., phone: '00123456789' }                  

Using Object.create

This is a very interesting way to create new objects. In this way, you can create a new object by taking another object as reference or prototype.

This means that the new object will keep the sample object as a reference in its prototype. The prototype values are accessible in the same way you can access other values.

One more thing to notice is that you can override any value present in the prototype. But the new object will have its own value without changing the prototype.

          const person = {   name: 'Full Name',   email: '[email protected]', };  const pankaj = Object.create(person);  console.log(pankaj); // 👈 → {} console.log(pankaj.name); // 👈 → 'Full Name'  person.name = 'Fullest Name';  console.log(pankaj.name); // 👈 → 'Fullest Name'  console.log(pankaj.__proto__); // 👆→ { name: 'Fullest Name', email: '[email protected]', phone: '00123456789' }  pankaj.name = 'Pankaj'; console.log(pankaj); // 👈 → { name: 'Pankaj' } console.log(pankaj.name); // 👈 → 'Pankaj' console.log(pankaj.__proto__.name); //👈 → 'Fullest Name'                  

And what if you wanna add some new properties to the object while creating the new object. This example shows us that:

          const person = {   name: 'Full Name',   email: '[email protected]', };  const pankaj = Object.create(person, {   website: { value: 'https://pankaj.pro/' } });                  

And the final object will look like following:


Using a Constructor Function i.e. with new keyword

Now you would more likely define a Class and then create an object from that class with the new keyword.

For a long time, JavaScript didn't have classes but still, it was Object-Oriented (OO). It achieved the OO by prototypal inheritance.

And a constructor function was a primary way to construct custom objects.

          const Person = function(name, email) {   this.name = name;   this.email = email;   return this; };  const person = new Person('Full Name', '[email protected]');                  

Later in ES6, JavaScript got the support of Class related keywords. And it reduced the complexity and learning curve for modern JavaScript.

Now you would more likely define a Class and then create an object from that class with the new keyword

          class Person {   constructor(name, email) {     this.name = name;     this.email = email;   } }  const person = new Person('Full Name', '[email protected]');                  

Conclusion

As you can see among these basic ways of creating the Objects in JavaScript; every approach has it use case.

So "which way do you usually use to create objects?".

Let me know through comments 💬 or on Twitter at @patel_pankaj_ and @time2hack

If you find this article helpful, please share it with others 🗣

Subscribe to the blog to receive new posts right to your inbox.

How Many Ways To Create Object In Javascript

Source: https://time2hack.com/different-ways-to-create-objects-in-javascript/

Posted by: rhodescapassicer.blogspot.com

0 Response to "How Many Ways To Create Object In Javascript"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel