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.