value = value ? value : null;
I want to set value
to null
if it is undefined
. Beside what I already have written, what else I can do with less repeating and more clean?
??
)You can use the nullish coalescing operator, which is a "[...] logical operator that returns its right-hand side operand when its left-hand side operand is null
or undefined
, and otherwise returns its left-hand side operand":
value = value ?? null;
This best fits your requirements to assign null
when value
is undefined
.
In combination with the assignment, this can be made even more concise by using the logical nullish assignment operator (??=
):
value ??= null;
This should meet all your requirements, but let's also look at some possible alternatives:
||
)Another alternative could be the ||
operator:
value = value || null;
Or in its assignment form:
value ||= null;
The difference here is that null
will be assigned for any falsy value, including 0
, false
, and ''
.
?:
)This is the original implementation from your question:
value = value ? value : null;
Essentially, this exhibits the same problem as the logical OR operator implementation in the sense that null
will be assigned for any falsy value. In this case, however, this can be mitigated by including a stricter comparison in the ternary condition (making it even more verbose):
value = value != null ? value : null;