What I want to is something like the following:
let x=32
let y=x===32 ?: 7;
My real life example would be more like the following:
inlineFunction(parameterWithLongNameIAmTesting===20000?parameterWithLongNameIAmTesting:anotherLongNameVariable);
Basically short circuiting the ternary. I want y to equal x if, and only if, x === 32. In the case above the value assigned to y would be 32. However if I had assigned x to equal 50 or anything else, then y would equal 7.
Is there a built-in way in javascript to do this?
You'd use 32 or x as the second operand:
let y = x === 32 ? x : 7;
Re:
The reason why I am looking for this is that in the real life situation I am using, the actual expression would look like this:
inlineFunction(parameterWithLongNameIAmTesting===20000?parameterWithLongNameIAmTesting:anotherLongNameVariable);It just looks really messy that way.
If it's just the mess, you can format it more clearly (IMHO) (SharedRory also makes this suggestion):
inlineFunction(
parameterWithLongNameIAmTesting === 20000
? parameterWithLongNameIAmTesting
: anotherLongNameVariable
);
Or if you don't like the repeated long names, you can use a local const:
const x = parameterWithLongNameIAmTesting;
inlineFunction(x === 20000 ? x : anotherLongNameVariable);
Is there a built-in way in javascript to do this?
Nothing other than the conditional operator above, or an if/else. You said in a comment you thought something had been added. You might be thinking of optional chaining (let y = something?.prop;) which short-circuits if something is null or undefined, resulting in undefined rather than the error something.prop would be. But that doesn't apply here.
Since you added an example, its common to see the following in a lot of code because its easy to read and not all on one line.
inlineFunction(
parameterWithLongNameIAmTesting === 20000
? parameterWithLongNameIAmTesting
: anotherLongNameVariable
);
Also formatters will usually do this too.
Not out of the box, but you can use a function like
eq = (a, b) => a === b ? a : undefined
in a combination with the null coalescing operator. Example:
eq = (a, b) => a === b ? a : undefined
test = 20000
defaultValue = 333
res = eq(test, 20000) ?? defaultValue
console.log(res)
test = 4444
defaultValue = 333
res = eq(test, 20000) ?? defaultValue
console.log(res)
As usual with functions, the advantage is that you can use them with arbitrary expressions, not just variables, for example:
return eq(computeChecksum(file), getStoredChecksum()) ?? '<failed>'