-1

I am not a JavaScript developer, but I just want to know the right way to check a variable contain a number or not. After a couple analysis I reached below solution. Is it correct way?

function calculation(n1,n2 , ...numbers) {

  let validateNumber = (num) => {
    if(num !== num)
      return 0;
      else
    return typeof num === 'number' ? num : 0;
  }

  let sum =0;
  for(n of numbers){
    sum += validateNumber(n);
  }
  console.log(sum);
} 

calculation(5,6,7,'gg','',null, NaN, undefined,  null,8,9,5.4,10);

Please check the 'validateNumber' arrow function.

Deepak Koshy
  • 230
  • 3
  • 9

5 Answers5

3

First version =>
-- simply use isNaN() : sum+(isNaN(val)?0:Number(val)

Second version (asked in comment here) =>
-- just use a strict comparison. to get only numeric type values.

const calculation =(...numbers)=>  // (n1,n2 , ...numbers)=>
  numbers.reduce((sum,val)=>
    sum + (Number(val)===val ? val : 0)  // sum+(isNaN(val)?0:Number(val))
    , 0);

console.log( calculation(5,6,7,'gg','',null, NaN, undefined,  null,8,9,5.4,'10') )

For more clarity, here it is a table showing the execution of the test according to the different possible types

const
  testFunction = val => Number(val)===val
, values =
  [ { v: 123,       display: `123`,       expected: true  }
  , { v: '123',     display: `"123"`,     expected: false }
  , { v: NaN,       display: `NaN`,       expected: false }
  , { v: undefined, display: `undefined`, expected: false }
  , { v: null,      display: `null`,      expected: false }
  ]
, tBody = document.querySelector('table > tbody')
  ;
let score = 0
  ;
for (let {v, display, expected} of values)
  {
  let
    TR  = tBody.insertRow()
  , res = testFunction(v)
    ;
  score += expected===res ? 1 : 0
  TR.insertCell().textContent = display
  TR.insertCell().textContent = expected
  TR.insertCell().textContent = res
  TR.insertCell().className   = expected===res ? 'ok' : 'bad'
  }
document.querySelector('table >tfoot td:nth-of-type(2)')
  .textContent = `${score} / ${values.length}`
table { font-family: Arial, Helvetica, sans-serif;border-collapse: collapse;margin: 0 1em; }
td    { padding: .2em .8em;border: 1px solid darkblue; } 
thead,tfoot {  background-color: #84a4ce;text-transform: capitalize; }
caption     { padding: .3em;caption-side: bottom;font-size: .8em; }
.ok:before,.bad:before { font-weight: bold;font-size: 1.2em; }
.ok:before  { color: green;content: '\2713'; }
.bad:before { color: red;  content: '\2718'; }
<table>
  <caption>( Number(val)===val ) ?</caption>
  <thead>
    <tr> <td>val</td><td>expected</td><td colspan="2">result</td> </tr>
  </thead>
  <tbody></tbody>
  <tfoot>
    <tr> <td colspan="3">score</td><td>0/0</td> </tr>
  </tfoot>
</table>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • 1
    @Andy because there are the 2 arguments n1 and n2 before – Mister Jojo Oct 02 '21 at 04:04
  • @Jojo don't mid the calculation part it is only for testing purpose . I am looking for easy and alternative condition in 'validateNumber ' . – Deepak Koshy Oct 02 '21 at 04:35
  • @Jojo Sorry for the complexity . the code snippet is part of my learning activity . I was looking into the Rest parameter concept , so the additional parameters n1 and n2 :) . Any way my doubt is regarding alternative approaches for verifying a given value is number or not . – Deepak Koshy Oct 02 '21 at 05:05
  • @Jojo :) I am looking for better approach for verifying a given value is number or not. Please stick to the point. I don't prefer to use isNaN() . – Deepak Koshy Oct 02 '21 at 07:13
  • @Jojo Your code sample fails at this point calculation(5,6,7,'gg','',null, NaN, undefined, null,8,9,5.4,'10'); . It still generate same output . Please show some respect to my question. isNaN() cause a type conversion. – Deepak Koshy Oct 02 '21 at 07:53
  • @DeepakKoshy I added a table allowing to see the results of this function in correspondence with the different possible types (see 2th snippet while opened) – Mister Jojo Oct 02 '21 at 17:43
1

Yes, there is built in function in JavaScript to check if a certain value is number or not which is isNaN()

If you want to get the sum of all the numbers in the array then you can try using reduce() like the following way:

var data = [5,6,7,'gg','',null, NaN, undefined,  null,8,9,5.4,10];
var sum = data.reduce((a,c) =>{
  if(!isNaN(c)){
    a = a + Number(c); //convert the '' and null to 0 with Number()
  }
  
  return a;
},0);
console.log(sum)
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

Yes it is a one liner also

export const isNum = n => Number(n) === Number(n);

First parse to number what Eva param you get them compare to itself. One of them what the hell's that comes with JavaScript is that NaN !== NaN so if the value you get after forcing it to be a number become s a Nan it will be different from itself

JS Disciple
  • 318
  • 1
  • 7
0

You can filter out the elements that aren't numbers by checking to see if they're not null and also a number, and then using reduce to sum up the elements.

function calculation(n1, n2, ...elements) {
  
  return elements

    // `filter` out the elements that are numbers
    .filter(el => el && Number(el))

    // Add them all up
    .reduce((acc, c) => acc + c, 0);
}

console.log(calculation(5,6,7,'gg','',null, NaN, undefined,  null,8,9,5.4,10));
Andy
  • 61,948
  • 13
  • 68
  • 95
0

Simple:

function isNumber(n) {
    return n === Number(n);
}
Dmitry Shashurov
  • 1,148
  • 13
  • 11