Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
Ternary function return Nan in Node js

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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;
}
about 4 years ago · Juan Pablo Isaza Report

0

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;
}
about 4 years ago · Juan Pablo Isaza Report

0

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;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!