13

Does Javascript / ES6 support the Elvis operator?

Example:

var x = (y==true) ?: 10;

Example 2:

var debug = true;
debug ?: console.log("Value of x:" + x);
6
  • 11
    No, there is no Elvis operator but you can use the || - var x = y || 10 for example or debug || console.log()
    – VLAZ
    Commented Oct 17, 2018 at 6:07
  • Apart from what @vlaz said, you could also do one line if statements if (y === true) 10; Note that this is not the most popular way of writing if statements cause of lack of readability.
    – Baruch
    Commented Oct 17, 2018 at 6:10
  • 1
    || is the Elvis operator. Commented Oct 17, 2018 at 6:43
  • @SalmanA || only evaluates if the condition is false. The Elvis operator evaluates if the condition is true. So && is closer to the Elvis operator. Commented Oct 17, 2018 at 6:50
  • @1.21gigawatts no. Refer to the definition on wiki which says that returns its first operand if that operand is considered true, and otherwise evaluates and returns its second operand. This is what || does: 1 || 2 // 1 vs 1 && 2 // 2. Commented Oct 17, 2018 at 6:55

2 Answers 2

12

No, but you can just use || or &&, seems to perform same function.

var debug = true;
debug && console.log("debug mode on ");
debug || console.log("debug mode off");
1
  • You could mark it as selected also 😀
    – Mild Fuzz
    Commented Oct 18, 2018 at 5:48
4

The short answer to your answer is "No". There is no Elvis operator in javascript. But you can achieve the same behavior in a few different short ways like so:

Using plain ternary operator:

var x = y ? 10 : null;

Or using a simple 'if' for just a single output:

if (debug) console.log("Value of x:", x);

Not the answer you're looking for? Browse other questions tagged or ask your own question.