β¨ 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 }
`
π 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)