Rex
Rex

Reputation: 169

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.

Upvotes: 0

Views: 178

Answers (2)

Syed Talha Salman
Syed Talha Salman

Reputation: 1

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

Upvotes: 0

Barmar
Barmar

Reputation: 781059

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]);

Upvotes: 1

Related Questions