JavaScript: Enhanced Object Literals (In-Depth)
Enhanced object literals (introduced in ES2015/ES6) make it easier and more concise to write and manage objects in JavaScript.
Key Features
- Property shorthand: Use variable names as property names directly.
- Method shorthand: Define functions without the
function keyword.
- Computed property names: Use expressions inside
[] for dynamic property names.
Property Shorthand
let x = 10, y = 20;
let point = { x, y };
// Equivalent to: { x: x, y: y }
// Output:
{ x: 10, y: 20 }
Method Shorthand
let person = {
name: "Alice",
greet() {
return "Hello, " + this.name;
}
};
// Equivalent to greet: function() { ... }
// Output:
"Hello, Alice"
Computed Property Names
let key = "score";
let player = {
[key]: 42,
["level" + 1]: "Beginner"
};
// Output:
{ score: 42, level1: "Beginner" }
Combining All Features
let kind = "shark";
let animal = {
kind,
["fin" + "Count"]: 2,
swim() { return "Swimming..."; }
};
// Output:
{ kind: "shark", finCount: 2, swim: ƒ }
Benefits
- Write less code, fewer bugs.
- More dynamic and flexible object creation.
- Methods are easier to read and maintain.
Practice: Use enhanced object literals in your functions, classes, and when returning objects from functions for cleaner code!