Conditional properties
const obj = {
...(condition && { prop: value })
}
Default values
If you wanna have values with variants in an object you usually do this, which is annoying:
color: {
default: 'gray',
light: 'lightGray',
dark: 'darkGray'
}
Instead, do this:
color: Object.assign('gray', {
light: 'lightGray',
dark: 'darkGray'
})
Now you can access the default value with color
instead of color.default
. Thanks to Max Stoiber for this tip.
Destructuring an array
@swyx shares this great tip on Twitter, again proving that I will never learn all of the secrets of objects in JavaScript.
const getFirstLast = (array) => {
const { 0: first, length: len, [len - 1]: last } = array
return { first, last }
}
getFirstLast('apple')
// {first: "a", last: "e"}
getFirstLast([1, 2, 3, 4, 5, 6])
// {first: 1, last: 6}