Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
ES6 introduced three major improvements to object literal syntax: property shorthand, method shorthand, and computed property names. Write less code to create objects!
const name = 'Alice';
const age = 25;
const city = 'Boston';
const user = {
name: name, // Repetitive!
age: age, // Repetitive!
city: city // Repetitive!
};
console.log(user);
// { name: 'Alice', age: 25, city: 'Boston' }const name = 'Alice';
const age = 25;
const city = 'Boston';
const user = {
name, // Same as name: name
age, // Same as age: age
city // Same as city: city
};
console.log(user);
// { name: 'Alice', age: 25, city: 'Boston' }When variable name matches property name
const person = {
name: 'Alice',
greet: function() {
console.log('Hello!');
},
sayName: function() {
console.log(this.name);
}
};
person.greet(); // Hello!
person.sayName(); // Aliceconst person = {
name: 'Alice',
greet() {
console.log('Hello!');
},
sayName() {
console.log(this.name);
}
};
person.greet(); // Hello!
person.sayName(); // AliceCleaner method definitions
const field = 'username';
const value = 'alice123';
// Create object first
const obj = {};
// Then add property
obj[field] = value;
console.log(obj);
// { username: 'alice123' }const field = 'username';
const value = 'alice123';
// Use [brackets] for computed key
const obj = {
[field]: value
};
console.log(obj);
// { username: 'alice123' }Dynamic property keys using expressions
const name = 'Alice';
const age = 25;
const field = 'email';
const user = {
// Property shorthand
name,
age,
// Computed property
[field]: 'alice@example.com',
[`is${name}`]: true,
// Method shorthand
greet() {
console.log(`Hi, I'm ${this.name}!`);
},
getInfo() {
return `${this.name} is ${this.age} years old`;
}
};
console.log(user);
// {
// name: 'Alice',
// age: 25,
// email: 'alice@example.com',
// isAlice: true,
// greet: [Function: greet],
// getInfo: [Function: getInfo]
// }Practical use of all enhancements
When variable name = key name{ name } instead of { name: name }
Drop function keywordgreet() { } instead of greet: function() { }
Use expressions as keys[key]: value or [`prefix_${name}`]: val