How to use ES6 Object Literal Property Value Shorthand in JavaScript

published: 15 Jun 2022

2 min read

ES6 Object Literal Property Value Shorthand in JavaScript

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, userEmail: email, age };

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

How to use ES6 Object Literal Property Value Shorthand in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming