Code should be readable, so being succinct should not mean being terse whatever the cost - for that you should repost to https://codegolf.stackexchange.com/ - so instead I would recommend using a second local variable named index
to maximize reading comprehensibility (with minimal runtime cost too, I note):
var index = someArray.indexOf( 3 );
var value = index == -1 ? 0 : index;
But if you really want to cut this expression down, because you're a cruel sadist to your coworkers or project collaborators, then here are 4 approaches you could use:
1: Temporary variable in a var
statement
You can use the var
statement's ability to define (and assign) a second temporary variable index
when separated with commas:
var index = someArray.indexOf(3), value = index !== -1 ? index: 0;
2: Immediately-Invoked Function Expression (IIFE)
Another option is an anonymous function
which is invoked immediately after it’s defined:
// Traditional syntax:
var value = function( x ) { return x !== -1 ? x : 0 }( someArray.indexOf(3) );
// ES6 syntax:
var value = ( x => x !== -1 ? x : 0 )( someArray.indexOf(3) );
3: Comma operator
There is also the infamous "comma operator" which JavaScript supports, which is also present in C and C++.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression.
You can use it to introduce side-effects, in this case by reassigning to value
:
var value = ( value = someArray.indexOf(3), value !== -1 ? value : 0 );
This works because var value
is interpreted first (as it's a statement), and then the left-most, inner-most value
assignment, and then the right-hand of the comma operator, and then the ternary operator - all legal JavaScript.
4: Re-assign in a subexpression
Commentator @IllusiveBrian pointed out that the use of the comma-operator (in the previous example) is unneeded if the assignment to value
is used as a parenthesized subexpression:
var value = ( ( value = someArray.indexOf(3) ) !== -1 ? value : 0 );
Note that the use of negatives in logical expressions can be harder for humans to follow - so all of the above examples can be simplified for reading by changing idx !== -1 ? x : y
to idx == -1 ? y : x
- or idx < 0 ? y : x
.
var value = ( ( value = someArray.indexOf(3) ) == -1 ? 0 : value );