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:

  1. Property value shorthands
  2. Method shorthands
  3. 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

  1. Create a property with property value shorthands
  2. Create a method with method shorthands
  3. Add two dynamic variables into Javascript with computed property names

Answers

  • Create a property with property value shorthands
const name = 'Zell'
const gender = 'male'

const zell = {
  name,
  gender
}

console.log(zell.name) // Zell
console.log(zell.gender) // male
  • Create a method with method shorthands
const zell = {
  sayMyName: function () { 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 Liew