ES6 gives you three JavaScript object enhancements. These enhancements are collectively called Enhanced Object literals. These enhancements are:
- Property value shorthands
- Method shorthands
- The ability to use computed property names
Property value shorthands
When you create objects, you may assign variables to properties that have the same name.
const fullName = 'Zell Liew'
const Zell = { fullName: fullName,}Property value shorthands lets you omit the assignment part (: fullName) if your property name and variable name are the same.
const fullName = 'Zell Liew'
const Zell = { fullName,}
// Underneath the hood, Javascript does this:const Zell = { fullName: fullName,}Method shorthands
When you declare a method, you need to write a function expression, like this:
const Zell = { sayMyName: function () { console.log("I'm Zell") },}Method shorthands lets you omit the : function part.
const Zell = { sayMyName() { console.log("I'm Zell") },}Computed object property names
If you need to create a property name through a variable, you had to use the bracket notation:
const property = 'name'obj[property] = 'Zell'Computed object property names lets you create objects with variables as property keys. To do so, you wrap the property with square brackets.
const property = 'name'const person = { [property]: 'Zell',}
console.log(person.name) // ZellYou can even change the property name while creating it.
const property = 'name'const person = { [property]: 'Zell', ['full' + property]: 'Zell Liew',}
console.log(person.fullname) // Zell LiewExercise
- Create a property with property value shorthands
- Create a method with method shorthands
- Add two dynamic variables into Javascript with computed property names
Create a property with property value shorthands
const name = 'Zell'const gender = 'male'
const zell = { name, gender,}
console.log(zell.name) // Zellconsole.log(zell.gender) // maleCreate a method with method shorthands
const zell = { sayMyName() { console.log("I'm Zell") },}Add two dynamic variables into Javascript with computed property names
const property = 'name'const person = { [property]: 'Zell', ['full' + property]: 'Zell Liew',}
console.log(person.fullname) // Zell LiewWelcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson