You’ve definitely written this kind of code:
const name = "John";
const age = 25;
const user = {
name: name,
age: age
};
It works… but it feels repetitive.
Now imagine doing this across a big app — configs, payloads, state objects…
👉 That repetition adds up fast.
That’s exactly why object shorthand properties exist. Small feature… but once you start using it, you won’t go back.
⚡ What Object Shorthand Actually Does
Simple rule:
👉 If key name = variable name, you can skip the value
const name = "John";
const age = 25;
const user = {
name,
age
};
Same result. Less noise.
🔎 Why This Matters (More Than You Think)
It’s not just about saving a few characters.
👉 It improves readability
Compare:
const payload = {
userId: userId,
token: token,
isAdmin: isAdmin
};
vs
const payload = {
userId,
token,
isAdmin
};
Second one is way easier to scan.
🔥 Real Use Case: API Payloads
This is where you’ll use it a lot.
function createUser(name, email) {
return {
name,
email,
createdAt: Date.now()
};
}
👉 Clean, minimal, and obvious.
🔥 Mixing Shorthand + Normal Properties
You don’t have to go all-in.
const id = 1;
const name = "John";
const user = {
id,
name,
role: "admin"
};
👉 Works perfectly fine.
🧠 Method Shorthand (Bonus)
This one is often grouped with object shorthand.
Instead of:
const user = {
greet: function () {
console.log("Hello");
}
};
You can write:
const user = {
greet() {
console.log("Hello");
}
};
👉 Cleaner and more modern.
💡 Real Developer Insight
This feature shines in:
- Redux-like state updates
- API request bodies
- Config objects
- Function return values
Basically… anywhere you’re building objects from existing variables.
Also:
👉 It reduces bugs.
Less repetition = fewer chances of mismatching keys and values.
⚠️ Where Things Get Confusing
1. ❌ Variable name mismatch
const username = "John";
const user = {
name // ❌ undefined variable
};
2. ❌ Overusing shorthand in unclear contexts
const a = 1;
const b = 2;
const obj = { a, b };
👉 Works… but not very descriptive.
Sometimes explicit naming is better.
3. ❌ Shadowing variables
const id = 1;
function create(id) {
return { id };
}
👉 Works, but be aware of scope — easy to confuse.
🚀 Best Practice Summary
✅ Use shorthand when key and variable names match
✅ Combine shorthand with explicit properties when needed
✅ Use method shorthand for cleaner object methods
✅ Avoid shorthand when it reduces clarity
✅ Prefer readability over saving characters
0 Comments