DEV Community

Usama
Usama

Posted on

πŸ€– Computed Property & ✨ Shorthand Property in JavaScript

✨ Shorthand Property

When the key and the variable name are the same in an object,

you don’t need to repeat them.

βœ… Example:

let name = "Usama";
let age = 22;

const user = {
  name, // shorthand for name: name
  age   // shorthand for age: age
};

console.log(user); 
// { name: "Usama", age: 22 }
Enter fullscreen mode Exit fullscreen mode


`

πŸ‘‰ This makes code cleaner and less repetitive.


πŸ€– Computed Property

Sometimes you want to dynamically set object keys.
You can use square brackets [] inside an object to compute the key.

βœ… Example:

`js
let key = "email";

const user = {
name: "Usama",
[key]: "usama@example.com" // computed property
};

console.log(user);
// { name: "Usama", email: "usama@example.com" }
`

πŸ‘‰ Here, the key is calculated at runtime.


πŸš€ Quick Recap

  • ✨ Shorthand Property β†’ Removes repetition (name, age)
  • πŸ€– Computed Property β†’ Allows dynamic keys ([key]: value)

Both make your code shorter, cleaner, and smarter 🎯


πŸ’‘ What’s your favorite JavaScript shorthand trick? Drop it in the comments! πŸ™Œ

`

Top comments (0)