Ternary function return Nan in Node js

Viewed 59

Code:

function sumfunct(x,y)
{
    let sum = 0;
    sum = (x === null ? 0 : x) + (y === null ? 0 : y);
    return sum;
}

if one of the input values are null then it returns Nan

Please help me to return some value

6 Answers

Add default values to your function arguments.

const sum = (x = 0, y = 0) => x + y;

In case they are null or undefined values will be 0;

For a better handle you can use something like:

const sum = (x, y) => {
  const a = Number.isFinite(+x) ? +x : 0;
  const b = Number.isFinite(+y) ? +y : 0;
  return a + b;
}

The logic operator === matches both type and value. If you don't pass an argument the default value is undefined which is not null, hence you add a number to undefined.

function sumfunct(x,y)
{
    let sum = 0;
    sum = (!x ? 0 : x) + (!y ? 0 : y);
    return sum;
}

In JavaScript all those values: (0, undefined, null, false, '') Will return false.

If you use the triple = like ===. This check also the TYPE. So if you have undefined as a value, this will not be === to null.

Check the simple function here, this may solve your problem.

function sumfunct(x,y)
{
    let sum = 0;
    sum = (x ? x : 0) + (y ? y : 0);
    return sum;
}

You can pass the default value as a 0.undefine and null replace with 0

function sumfunct(x=0,y=0)
{
    let sum = 0;
    sum = x + y;
    return sum;
}

sumfunct(console.log(sumfunct(2, undefined)))
sumfunct(console.log(sumfunct(2, null)))

You can just check both inputs separately as well

function sumfunct(x,y)
{
    x = (x === null ? 0 : x);
    y = (y === null ? 0 : y);
    return x+y;
}

console.log(sumfunct(2,2));
console.log(sumfunct(2,null));

A shorter way to do it. Every falsey value (0, null or undefined) would be transform to 0:

function sumfunct(x,y)
{
    let sum = 0;
    sum = (x || 0) + (y || 0);
    return sum;
}

Try snippet here

function sumfunct(x,y)
{
    let sum = 0;
    sum = (x || 0) + (y || 0);
    return sum;
}

console.log(sumfunct(2, 2));   // 4
console.log(sumfunct(3));     // 3
console.log(sumfunct(null, 2));   // 2
console.log(sumfunct(undefined, undefined));   // 0

Related