ES6 Object Literal Property Value Shorthand in JavaScript

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.