Skip to main content

Property shorthand ({ x, y })

Property shorthand is syntactic sugar in JavaScript that lets you create an object more concisely when the property name matches the variable name.


The regular way (long form)

Before ES6 (or without shorthand) you would write it like this:

javascript
const x = 10; const y = 20; const point = { x: x, y: y }; console.log(point); // { x: 10, y: 20 }

Here the keys and the variables have the same names, so the notation looks redundant.


Shorthand notation (ES6 shorthand)

Now the same thing can be written more simply:

javascript
const x = 10; const y = 20; const point = { x, y }; console.log(point); // { x: 10, y: 20 }

When the property name matches the variable name, it is enough to state just the name - JS automatically creates the key: value pair.


How this works under the hood

javascript
{ x, y } // equivalent to { x: x, y: y }

Regular and shorthand properties can be mixed

javascript
const name = 'Tim'; const age = 25; const user = { name, age, country: 'Ukraine' }; console.log(user); // { name: 'Tim', age: 25, country: 'Ukraine' }

Example with a function

javascript
function createUser(name, age) { return { name, age }; } console.log(createUser('Oleh', 30)); // { name: 'Oleh', age: 30 }

This simplifies the code of factories and constructors, where the keys match the function parameters.


Can be combined with computed properties

javascript
const key = 'city'; const value = 'Lviv'; const obj = { [key]: value, country: 'Ukraine' }; console.log(obj); // { city: 'Lviv', country: 'Ukraine' }

Shorthand notation works alongside other object literal features.


Summary

NotationEquivalentWhat it does
{ x, y }{ x: x, y: y }Creates properties with the same names as the variables
{ name, age, country: 'Ukraine' }{ name: name, age: age, country: 'Ukraine' }Can be mixed
Works with functionsYesSimplifies returning objects

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.