The last three lines use a lot of syntax to communicate a simple intent.
foo is initialized to
null, signalling that there is no
Then the code attempts to get some Foos.
The intent is to reassign
foo only when
getFoos produces a
getFoos produces an empty array, there is no reason to change the
I wonder if it would be nice to have an “optional assignment” operator for a moment like this. An optional assignment operator would change the assignment only when an arbitrary expression has a truthy evaluation. Here’s a hypothetical syntax:
This is almost a ternary expression but it saves me from having to provide the initial value on the right side of the expression.
Only the optional assignment operator enables me to communicate my intent exactly.
The premise of my example is that I mean to write code in an imperative style
with mutable assignment.
Other styles of programming suggest other ways to model a nullable value.
Some of those ways render an optional assignment operator unnecessary.
Maybe monad from functional programming is one example.
There are also other ways to use less characters to implement roughly the same logic. For example:
undefined is used to signal the absence of value.
null for this purpose.
When null values are literally
null, then I can depend on
indicate something broken or unexpected.
Another example is:
This works only if
foos is expected to be truthy.
An array of booleans containing
false would break this logic.