It’s common to find yourself assigning a value to a variable that might or might not be null. A first-pass approach to coalescing a value into that variable might look like this:
1 2 3 4 5 6 7 | |
A more concise way would be to use the ternary operator:
1
| |
This is much better. It’s still readable, but is also more expressive. The third way (that I prefer) is to use a Boolean operator in assignment, like so:
1
| |
This works exactly like the ternary: if userInput is ‘falsey’, the evaluation of the Boolean continues, and Foo is assigned the value of defaultValue. If userInput is “truthy”, however, evaluation of the OR statement stops, because one side of the Boolean has evaluated to true.
A similar trick can be done using the AND operator:
1 2 3 | |
but
1 2 3 | |
These two way of conditionally assigning value to a variable can be used to make javascript quite expressive while maintaining readability. Go forth and code.