Skip to Content
All posts

Understanding Object Literal Enhancement In Javascript

OGBONNA SUNDAYOGBONNA SUNDAY
Β·
2 min read
Cover image for Understanding Object Literal Enhancement In Javascript

title: Understanding Object Literal Enhancement In Javascript published: true date: 2022-04-12 00:13:21 UTC tags: canonical_url: cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zyw1h7rhpz8sadipvky3.png

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}

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

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);
},
};

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....😎😎

More posts

Dec 2025I Patched CSS Grid into React Native β€” Here's What Broke (and What Finally Worked)
Oct 2024Level Up Your JS: Object Literal Enhancements That Will Change Your Code
Jul 2023Understanding getStaticProps in Next.js
Jul 2023How I Got Hired Contributing to open source projects
Jun 2023Leveraging OpenSauced AI to Generate Compelling PR Descriptions