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

226
Views
How to get the first number in input values of range number or undefined

I want to get the first number value out of values with number or undefined range.

Obviously this fails for 0 which is falsy. What is the logical expression to return this?

    type Nomber = number | undefined

    function a_or_b_or_c_number_value_including_zero(a: Nomber, b: Nomber, c: Nomber) {
      return (a || b || c)
    }

    const test = (a: Nomber, b: Nomber, c: Nomber, expected: any) => {
      let got = a_or_b_or_c_number_value_including_zero(a, b, c)
      if (got !== expected) {
        console.log([a, b, c], 'fail', got, expected)
      }
    }


test(1, 2, 3, 1)
test(undefined, 1, 2, 1)
test(0, 1, 2, 0)
test(undefined, 0, 2, 0)
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use the nullish coalescing operator to check it.

According to MDN:

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.


This can be used in your code like below.

function a_or_b_or_c_number_value_including_zero(a: Nomber, b: Nomber, c: Nomber) {
  return (a ?? b ?? c); // Modified
}

This will make the code work the way you want, which will not make 0 equal to false.


This is how the code works.

Code Description
a ?? If a isn't null or undefined, use a.
b ?? c If b is null or undefined, use c, else, use b.

In conclusion, the nullish coalescing operator is a useful feature to not make 0 and "" equal to false (while || evaluates those values to false).

about 4 years ago · Juan Pablo Isaza Report

0

Use ?? instead of ||

function a_or_b_or_c_number_value_including_zero(a: Nomber, b: Nomber, c: Nomber) {
      return (a ?? b ?? c)
    }
about 4 years ago · Juan Pablo Isaza Report

0

You can use the the Nullish coalescing operator (??) to workaround the 0 failing for being falsy.

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!