2

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
Community
  • 1
  • 1
Richard
  • 62,943
  • 126
  • 334
  • 542

4 Answers4

1

You can check the type of a in ternary operator.

var b = {
    items: typeof (+a) == 'number' ? +a : null
};

Demo:

var b = {
  items: typeof (+"0") == 'number' ? +"0" : null
};


alert(b.items);

EDIT

Hack to check null.

function f(a) {
  return isNaN('' + a) ? null : parseFloat(a)
}


alert(f(0));
alert(f(null));
alert(f(undefined));
Tushar
  • 85,780
  • 21
  • 159
  • 179
1

You could specifically test for null and undefined

var b = {
    items: ('undefined' === typeof a || null === a) ? null : +a
};
hair raisin
  • 2,618
  • 15
  • 13
0

Try this

var b = {
   items: +a ||(a==0?0:null)
};
Sky Fang
  • 1,101
  • 6
  • 6
0

This should work as well:

var b = {
   items: a != null? +a : null
};

Based on https://stackoverflow.com/a/15992131/1494833

Community
  • 1
  • 1
r0hitsharma
  • 1,592
  • 12
  • 16