Adding property to an object conditionally in JavaScript
1 min readJun 4, 2021
By using && operator, we can add property to an object conditionally. Say we want to add color
property to the following Car
object if it is produced after 2000. Doesn’t make much sense but for the sake of the example let’s pretend it does :) Here is how you can accomplish that:
const modelYear = 1996
const Car = {
brand: 'Toyota',
...(modelYear > 2000) && { color: 'red' }
}
The above code snippet will yield the following Car
object:
const Car = {
brand: 'Toyota',
color: 'red'
}
If you negate the condition, meaning say you have the following:
const modelYear = 2003
const Car = {
brand: 'Toyota',
...(modelYear > 2000) && { color: 'red' }
}
Then the resulting Car object would be:
const Car = {
brand: 'Toyota'
}
It is that simple. Have fun :)