DEV Community

Cover image for Understanding Object Literal Enhancement In Javascript
OGBONNA SUNDAY
OGBONNA SUNDAY

Posted on • Originally published at blog.ogbonna.dev on

Understanding Object Literal Enhancement In Javascript

Definition

Object literal enhancement is the opposite of destructuring. it's the process of restructuring or putting the object back together.

Remember in my previous blog, i talked about about Array and Object destructuring, and stated that destructuring is the process of unpacking a small part of something from the main part. Well, with object literal enhancement , we can grab variables from the global scope and add them to an object.

const name = "Tallac"
const elevation = 9738
const funHike = {name, elevation}
console.log(funHike); //{name: "tallac", elevation: 9738}

Enter fullscreen mode Exit fullscreen mode

name and elevation are now keys of the funHike object.

We can also create object methods with object literal enhancement or restructuring.

const name = "Tallac"
const elevation = 9738
const print = function(){
    console.log(`Mt. ${this.name} is ${this.elevation} feet tall`)
}
const funHike = {name, elevation, print}
funHike.print(); // Mt. Tallac is 9738 feet tall

Enter fullscreen mode Exit fullscreen mode

Notice we use this keyword to access the object keys.

When defining object methods, it's no longer necessary to use the function keyword.

//old
var skier = {
  name: name,
  sound: sound,
  powderYell: function () {
    var yell = this.sound.toUpperCase();
    console.log(`${yell} ${yell} ${yell}!!!`);
  },
  speed: function (mph) {
    this.speed = mph;
    console.log("speed", mph);
  },
};

// New
const skier = {
  name,
  sound,
  powderYell() {
    let yell = this.sound.toUpperCase();
    console.log(`${yell} ${yell} ${yell}!!!`);
  },
  speed(mph) {
    this.speed = mph;
    console.log("speed", mph);
  },
};

Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, Object Literal Enhancement allows us to pull global variables into object and reduce typing by making th function keyword unnecessary.

If you find this article helpful, then click on the follow button to get more updates and helpful resources on Javascript, ReactJs and NextJs.. You can also follow me on twitter @o_sunday15 to get useful resources and tech trends.

Don't forget to leave a comment on what you think and know also....😎😎

Top comments (0)