Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Property Shorthand

Property shorthand reduces repetition when object keys match variable names.

It keeps object literals short and readable.

Why We Need It

Shorthand improves readability in object creation and factory functions.

It is widely used in modern JavaScript.

Syntax

const obj = { name, role }
const obj = { greet() { ... } }

Basic Example

1. Property shorthand

const name = "Ava";
const role = "admin";
const user = { name, role };

console.log(user);

Shorthand uses variable names as keys.

Real World Example

2. Method shorthand

const user = {
  name: "Ava",
  greet() {
    return "Hi " + this.name;
  }
};

console.log(user.greet());

Methods can be defined without the function keyword.

Multiple Use Cases

Shorter Object Literals

Property shorthand lets you write { name } instead of { name: name }.

It makes object literals cleaner and less repetitive.

Method Shorthand

Methods can also use shorthand: greet() { ... }.

This keeps object definitions compact.

Use Cases

Shorthand is common when creating objects from variables.

It is especially useful in factory functions and reducers.

More Examples

3. Factory function

function createUser(name, role) {
  return { name, role };
}

console.log(createUser("Ava", "admin"));

Shorthand keeps factory functions concise.

4. Computed with shorthand

const key = "status";
const value = "active";
const obj = { [key]: value };

console.log(obj);

Combine shorthand with computed keys.

Comparison

Without

const user = { name: name, role: role };

With

const user = { name, role };

Common Mistakes and Fixes

Forgetting variable names

Shorthand only works when variable names match desired keys.

Overusing shorthand

Use explicit keys when it improves clarity.

Confusing method shorthand

Remember method shorthand still creates a function.

Interview Questions

What is property shorthand?

A shorter way to define object properties when key and variable name match.

Does shorthand change behavior?

No, it is just syntax sugar.

When is explicit better?

When the key name differs or clarity is needed.

Practice Problem

Practice: Create an object with name and age using shorthand.

const name = "Ava";
const age = 22;
// TODO: create object

One Possible Solution

const name = "Ava";
const age = 22;
const user = { name, age };
console.log(user);

Frequently Asked Questions

When can I use property shorthand?

When variable names match the object keys you want.

Is method shorthand different from function?

It is just shorter syntax; behavior is the same.

Can I use shorthand with computed keys?

Yes, using [key]: value syntax.

Try It Yourself

Try creating objects with different variable names.