This content originally appeared on DEV Community and was authored by Usama
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!
`
This content originally appeared on DEV Community and was authored by Usama