3 min read
•Question 48 of 50easyWhat are ES6 Object Property Shorthand and Computed Properties?
Understanding modern object syntax.
What You'll Learn
- Property shorthand
- Method shorthand
- Computed property names
Property Shorthand
code.jsJavaScript
const name = 'John';
const age = 30;
// Old way
const user1 = {
name: name,
age: age
};
// Shorthand
const user2 = { name, age };
// { name: 'John', age: 30 }Method Shorthand
code.jsJavaScript
// Old way
const obj1 = {
greet: function() {
return 'Hello';
}
};
// Shorthand
const obj2 = {
greet() {
return 'Hello';
},
async fetchData() {
return await fetch('/api');
}
};Computed Property Names
code.jsJavaScript
const prop = 'dynamicKey';
const index = 0;
const obj = {
[prop]: 'value', // dynamicKey: 'value'
['item' + index]: 'first', // item0: 'first'
[`key_${index}`]: 'data' // key_0: 'data'
};
// Dynamic keys with expressions
const fieldName = 'email';
const formData = {
[fieldName]: 'john@example.com',
[`${fieldName}Valid`]: true
};
// { email: 'john@example.com', emailValid: true }Combining Patterns
code.jsJavaScript
function createUser(name, age, role) {
const id = Date.now();
return {
id, // Shorthand
name, // Shorthand
age, // Shorthand
[role]: true, // Computed: { admin: true }
greet() { // Method shorthand
return `Hi, I'm ${this.name}`;
}
};
}