Enhanced Object Literals In JavaScript

Enhanced Object Literals In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Enhanced Object Literals In JavaScript.

Enhanced Object Literals In JavaScript

In JavaScript, “Enhanced Object Literals” is a shorthand notation for defining properties and methods on an object. This feature was introduced in ECMAScript 6 (ES6) and allows for a more concise and expressive syntax for defining objects.

Here is an example of how you can use the shorthand notation to define an object with properties and methods:

Code

let name = "John";
let age = 30;

let person = {
  name,  // same as name: name
  age,   // same as age: age
  sayHello() {  // same as sayHello: function(){}
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
};

console.log(person.name);
console.log(person.age);
person.sayHello();

Output

“John”

30

“Hello, my name is John and I am 30 years old.”

As you can see, with enhanced object literals, you can use the shorthand notation of “property” instead of “property: property” and “method()” instead of “method: function()” for defining properties and methods.

Also, you can use computed property names to define properties whose names are determined at runtime

let prop = 'name';
let obj = {
  [prop]: 'John',
  ['age']: 30,
  ['say'+'Hello']() { 
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
};

and default values for object properties

let obj = {
  name = 'John',
  age: 30,
  sayHello() { 
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
};

Conclusion

Overall, enhanced object literals make it easier to define objects with properties and methods and make the code more readable and maintainable.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment