In my JavaScript I currently have this nice expression:
var b = {
items: +a || null
};
This sets b.items
to a Number if a
is a String, or a Number greater than 0, and as null
if a
is null
/undefined
.
However, it also returns null
if a
is 0. Now I'd like to change it so that it returns 0 if a
is 0. (This seems like the right way to handle real data: if it's zero, we want to know that it's zero, and if it doesn't exist, we want to know that too.)
I've looked at this question and tried these two:
items: 1/a ? +a: null
items: isNaN(a) ? null : +a
but these both return 0 if a
is null. They should return null.
Is there a way I can return 0 if a
is 0, and null
if it's undefined?
Update: Here's a summary of everything the expression needs to do:
"72" -> 72
"0" -> 0
1 -> 1
0 -> 0
null -> null
undefined -> null