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

Let us look at the following example:

var name = 'John Doe';
var email = 'john.doe@example.com';
var age = 25;

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

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

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 = 'john.doe@example.com';
let age = 25;

let user = { name, email, age };

console.log(user);

// { 
//     name: 'John Doe', 
//     email: 'john.doe@example.com', 
//     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, e userEmail: email, age };

// { 
//     name: 'John Doe', 
//     userEmail: 'john.doe@example.com', 
//     age: 25 
// }

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

Last Updated: