Interview question
What are computed property names and shorthand property syntax in ES6 objects? ES6 objects में computed property names और shorthand property syntax क्या हैं?
Answer
ES6 added shortcuts for writing object literals more concisely, especially useful when variable names match property names or property names need to be dynamic.
// SHORTHAND PROPERTIES - when variable name matches key
const name = 'John';
const age = 30;
// Old way
const userOld = { name: name, age: age };
// ES6 shorthand
const user = { name, age };
console.log(user); // { name: 'John', age: 30 }
// SHORTHAND METHODS
const calculatorOld = {
add: function(a, b) { return a + b; }
};
const calculator = {
add(a, b) { return a + b; } // shorthand method syntax
};
console.log(calculator.add(2, 3)); // 5
// COMPUTED PROPERTY NAMES - dynamic keys using expressions
const propName = 'email';
const dynamicObj = {
[propName]: 'john@example.com', // key computed from variable
[`${propName}Verified`]: true // key computed from expression
};
console.log(dynamicObj); // { email: 'john@example.com', emailVerified: true }
// Practical use case - building objects from dynamic keys
function createFieldObject(fieldName, value) {
return { [fieldName]: value };
}
console.log(createFieldObject('username', 'john_doe'));
// { username: 'john_doe' }
// Combining shorthand and computed properties
function createUser(name, age) {
const idKey = 'userId';
return {
name, // shorthand
age, // shorthand
[idKey]: Math.random().toString(36).slice(2) // computed
};
}
console.log(createUser('John', 30));ES6 ने object literals को concisely लिखने के shortcuts दिए, खासकर जब variable names property names से match करते हों या property names dynamic हों।
// SHORTHAND PROPERTIES
const name = 'John';
const age = 30;
// पुराना तरीका
const userOld = { name: name, age: age };
// ES6 shorthand
const user = { name, age };
console.log(user); // { name: 'John', age: 30 }
// SHORTHAND METHODS
const calculatorOld = {
add: function(a, b) { return a + b; }
};
const calculator = {
add(a, b) { return a + b; }
};
// COMPUTED PROPERTY NAMES - dynamic keys
const propName = 'email';
const dynamicObj = {
[propName]: 'john@example.com',
[`${propName}Verified`]: true
};
console.log(dynamicObj); // { email: '...', emailVerified: true }
// Dynamic keys से objects बनाना
function createFieldObject(fieldName, value) {
return { [fieldName]: value };
}
console.log(createFieldObject('username', 'john_doe'));
// Shorthand और computed साथ
function createUser(name, age) {
const idKey = 'userId';
return {
name,
age,
[idKey]: Math.random().toString(36).slice(2)
};
}Was this answer clear?