In JavaScript, we are used to constructing an object by using the literal syntax {...} where each key-value pair is defined explicitly. We usually use the same object key names as the existing variables used as values.

Let us look at the following example:

var name = 'John Doe'
var email = ''
var age = 25

var user = {
  name: name,
  email: email,
  age: age

As you can see above, the properties have the same names as the variables. The object literal property value shorthand was introduced in ES6 to shorten the object initialization.

It allows us to define an object whose keys have the same names as the variables passed in as properties by simply passing the variables:

let name = 'John Doe'
let email = ''
let age = 25

let user = { name, email, age }


// {
//     name: 'John Doe',
//     email: '',
//     age: 25
// }

The property value shorthand syntax automatically converts each variable to a key-value pair with the variable name as a property key and the variable value as a property value.

You can also combine both regular properties and shorthands in the same object. This is especially useful when you want to assign a different key name to a property than the variable name:

let user = { name, userEmail: email, age }

// {
//     name: 'John Doe',
//     userEmail: '',
//     age: 25
// }

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.