ES6+ allows you to write object literals in a more concise way.
Property Shorthand
When you have variables with the same name as the object properties you want to create, you can use the property shorthand.
Traditional Syntax:
const name = "Alice";
const age = 25;
const person = {
name: name,
age: age
};
Enhanced Object Literal Syntax:
const name = "Alice";
const age = 25;
const person = { name, age };
In the enhanced version, if the variable name is the same as the property name, you only need to write it once.
Method Shorthand
Instead of defining methods using the function keyword, you can define them more succinctly.
Traditional Syntax:
const calculator = {
add: function(a, b) {
return a + b;
}
};
const sum1 = calculator.add(3, 4); // Calls the add function with 3 and 4, returning 7
console.log(sum1); // 7
const sum2 = calculator["add"](5, 6); // Using bracket notation to call the function, returning 11
console.log(sum2); // 11
Enhanced Object Literal Syntax:
const calculator = {
add(a, b) {
return a + b;
}
};
const sum1 = calculator.add(3, 4); // Calls the add function with 3 and 4, returning 7
console.log(sum1); // 7
const sum2 = calculator["add"](5, 6); // Using bracket notation to call the function, returning 11
console.log(sum2); // 11
This shorthand not only reduces code but also makes the object literal cleaner and easier to read.
Computed Property Names
This feature lets you use an expression as a property name by wrapping it in square brackets. This is useful when the property name needs to be dynamic.
Example:
const key = "favoriteColor";
const person = {
name: "Bob",
[key]: "blue" // The property name becomes the value of 'key'
};
console.log(person);
// Output: { name: "Bob", favoriteColor: "blue" }
You can even compute the property name using more complex expressions, making your objects flexible and dynamic.
Why Use Enhanced Object Literals?
Conciseness:
They reduce redundancy, especially when variable names and property names match.
Readability:
Cleaner syntax means your code is easier to understand and maintain.
Flexibility:
Computed property names allow for dynamic keys, which is very useful in many coding scenarios.
Putting It All Together
Here’s an example combining all three features:
const firstName = "Charlie";
const lastName = "Brown";
const dynamicKey = "hobby";
const person = {
firstName,
lastName,
// Method shorthand
getFullName() {
return `${this.firstName} ${this.lastName}`;
},
// Computed property name
[dynamicKey]: "Baseball"
};
console.log(person.getFullName()); // "Charlie Brown"
console.log(person.hobby); // "Baseball"
In this example:
- Property shorthand is used for
firstNameandlastName. - Method shorthand is used to define
getFullName. - Computed property name is used to set the
hobbyproperty dynamically.
Enhanced Object Literals are a small but powerful feature that can greatly improve the clarity and brevity of your code.