Enhanced Object Literals
Hey ,
I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.
Please upgrade (use this link) access this content.
I'm super eager to help you learn more!
Enhanced Object Literals
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) // Zell
You 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 Liew
Exercise
- Create a property with property value shorthands
- Create a method with method shorthands
- Add two dynamic variables into Javascript with computed property names