1

I have this code line:

const my_v = !isNaN(parseInt(jQuery('#id').val())) ? parseInt(jQuery('#id').val()) : 0;

As you can see I call the parseInt function twice.
I was wondering if there is a way to do that assignment calling the function once.

Giacomo M
  • 4,450
  • 7
  • 28
  • 57

4 Answers4

5

The result of parseInt() is going to be either a number or NaN, so you can use ||:

const my_v = parseInt(jQuery("#id").val()) || 0;

Now, in general I would caution anyone against using parseInt(), because (by design) it accepts strings like "123hello world" as valid numbers (123 in this case). You can use the Number() constructor or plain unary + to coerce a string to a number. If you don't want a fractional part, you can use Math.floor() or Math.round(), and you can check numerically to see if there's a fractional part if that should be considered an error.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

Sure using an IIFE:

 (n => !isNaN(n) ? n : 0)(parseInt(jQuery('#id').val()))

But seriously, usea local variable.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

With one const you can declare more than one variable.

const idValue = parseInt(jQuery('#id').val()), my_v = isNaN(idValue) ? 0 : idValue;
mbojko
  • 13,503
  • 1
  • 16
  • 26
0

If you have already a stringed integer value, you could just take a number or zero as default value.

const my_v = +jQuery('#id').val() || 0;

If not, get first the value and then the integer part.

const my_v = Math.floor(+jQuery('#id').val() || 0);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392