Add conditional properties using
A simple technique is using an if statement to conditionally add members:
There are no thrills to this technique, but it’s straight forward.
Add conditional properties using logical and spread operators
For a shorter syntax, ES5 introduced the ability to do this:
The snippet above is processed as follows: starting from left and traversing right, the first operand that is evaluated as
falsy is returned. In the expression above, there are no
falsy operands so the right-most is returned.
spread operator has a lower precedence than the
&& operator because the underlying implementation uses
If the condition is false:
The spread operation will be result in nothing being added.