What are Enhanced Object Literals?
Enhanced Object Literals were introduced in ES6 to simplify object creation syntax. They make JavaScript objects more concise, readable, and powerful.
With enhanced object literals, you can:
- Use shorthand property names when the property name matches the variable name.
- Define methods directly inside objects without the
function
keyword. - Use computed property names to dynamically name object keys.
1. Shorthand Property Names
If the variable name and object key are the same, you can skip the key-value syntax.
const name = "Alice";
const age = 28;
const person = {
name,
age
};
console.log(person);
Output:
{ name: 'Alice', age: 28 }
Why does this work?
JavaScript assumes name: name
and age: age
, so the shorthand saves you from repetition.
2. Shorthand Method Definitions
You can define methods inside objects without using the function
keyword.
const calculator = {
add(x, y) {
return x + y;
},
subtract(x, y) {
return x - y;
}
};
console.log(calculator.add(10, 5));
console.log(calculator.subtract(10, 5));
Output:
15 5
Question:
Can you use this method shorthand for arrow functions?
Answer: No, method shorthand only works for regular function declarations. Arrow functions are not suited for object methods because they don't have their own this
.
3. Computed Property Names
You can use square brackets to define keys dynamically in objects.
const key = "userId";
const value = 101;
const user = {
[key]: value,
name: "Bob"
};
console.log(user);
Output:
{ userId: 101, name: 'Bob' }
Use Case Example
Suppose you're creating a function that returns a config object with dynamic properties:
function createConfig(option, isEnabled) {
return {
[option]: isEnabled,
timestamp: Date.now(),
log() {
console.log(`${option} is ${isEnabled ? "enabled" : "disabled"}`);
}
};
}
const config = createConfig("darkMode", true);
config.log();
console.log(config);
Output:
darkMode is enabled { darkMode: true, timestamp: 1683038293871, log: [Function: log] }
Key Takeaways
- Enhanced object literals reduce redundancy and improve readability.
- Use shorthand syntax when variable and key names match.
- Use method shorthand for cleaner object functions.
- Use computed properties for dynamic key generation.
Quick Recap Questions
Q: What happens if you write { x }
inside an object when let x = 10
?
A: It's equivalent to { x: 10 }
.
Q: Can you use expressions inside computed property names?
A: Yes, for example: { [`prop${1+1}`]: "value" }
results in { prop2: "value" }
.