0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Shorthand Property in JavaScript: Simple Guide

In JavaScript, shorthand property lets you create object properties using just the variable name when the property name and variable name are the same. Instead of writing { name: name }, you can simply write { name } inside an object literal.
📐

Syntax

The shorthand property syntax allows you to write object properties more concisely when the property name matches the variable name.

  • Without shorthand: { propertyName: variableName }
  • With shorthand: { propertyName } (when propertyName and variableName are the same)
javascript
const name = 'Alice';
const age = 30;

const person = {
  name: name,  // long form
  age: age     // long form
};

const personShorthand = {
  name,       // shorthand
  age         // shorthand
};
💻

Example

This example shows how to create an object using shorthand properties to make the code shorter and easier to read.

javascript
const city = 'Paris';
const country = 'France';

const location = { city, country };

console.log(location);
Output
{"city":"Paris","country":"France"}
⚠️

Common Pitfalls

One common mistake is trying to use shorthand when the variable name and property name are different. This will cause the property to be undefined or unexpected.

Also, shorthand only works inside object literals, not in other places.

javascript
const firstName = 'John';

// Wrong: property name and variable name differ
const person = { name }; // ReferenceError: name is not defined

// Correct:
const personCorrect = { name: firstName };
📊

Quick Reference

ConceptExampleDescription
Long form{ name: name }Property name and variable name written fully
Shorthand{ name }Property name same as variable name, shorthand used
Invalid shorthand{ name } when variable is differentCauses error or undefined property

Key Takeaways

Use shorthand property when the property name and variable name are the same to write cleaner code.
Shorthand properties only work inside object literals.
Avoid using shorthand if variable and property names differ to prevent errors.
Shorthand makes object creation shorter and easier to read.