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

151
Views
Ternary Operator using part of the condition as the result Javascript

In a ternary or if statement, I often want the value to equal the value of what is being tested for example

//b is a integer or '-'
//a should be an integer

const a = b === '-' ? -1 : b

The statement I am using for a is

const a = expr.match(/.*?\((.*)[a-z].*/)[1]

so it would be nice to know if there is a single line way to have it work so i'm not repeating a complicated expression that may change.

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

0

Just assign the variable first.

let b = b = expr.match(/.*?\((.*)[a-z].*/)[1];
const a = b == '-' ? -1 : b;

If you really want a one-liner, you can assign b within the expression.

const a = (b = expr.match(/.*?\((.*)[a-z].*/)[1]) == '-' ? -1 : b;

But you should have declared b earlier. You can reuse the same temporary variable every time, so you only have to declare it once and use it in all the one-liners.

If you need this pattern in multiple places, define a function.

function if_dash(expr) {
    return expr == '-' ? -1 : expr;
}

const a = if_dash(expr.match(/.*?\((.*)[a-z].*/)[1]);
about 4 years ago · Juan Pablo Isaza Report

0

If you want to get value only one time use below mentioned script. var a = (b = expr.match(/.*?\((.*)[a-z].*/)[1]) == '-' ? -1 : b;

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!