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

149
Views
Trying to simplify this JavaScript expression dealing with undefined

I want to preserve the undefined if pinned is actually undefined, otherwise, I want to set the value across the equals sign to 1 if pinned is true and 0 if it's false. I came up with this that works, but I keep looking at it and it seems like it should be simpler.

const resultingValue = pinned === undefined ? undefined : pinned ? 1 : 0;

What I'm wanting is:

if pinned is undefined, return undefined if pinned is true, return 1 if pinned is false, return 0 otherwise, return 0;

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

0

You could check type and return either a number of boolean or undefined.

const
    resultingValue = typeof pinned === 'boolean'
        ? +pinned
        : undefined;
about 4 years ago · Juan Pablo Isaza Report

0

Works for: true, false, undefined, 0, 1

const resultingValue = +pinned + 1 ? +pinned: undefined;
about 4 years ago · Juan Pablo Isaza Report

0

Use a lookup table for each value. The undefined can be omitted since it is going to produce undefined by default:

const lookup = {true: 1, false: 0};
const convert = value => 
  lookup[value];

console.log(convert(true));
console.log(convert(false));
console.log(convert(undefined));
console.log(convert());

This can be shortened to a single function, if desired:

const convert = value => 
  ({true: 1, false: 0}[value]);

console.log(convert(true));
console.log(convert(false));
console.log(convert(undefined));
console.log(convert());

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!