12

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);
1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231
  • 11
    No, there is no Elvis operator but you can use the `||` - `var x = y || 10` for example or `debug || console.log()` – VLAZ Oct 17 '18 at 06: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 Oct 17 '18 at 06:10
  • 1
    `||` _is_ the Elvis operator. – Salman A Oct 17 '18 at 06: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. – 1.21 gigawatts Oct 17 '18 at 06: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`. – Salman A Oct 17 '18 at 06:55
  • The `?:` operator will evaluate the right hand condition if the left hand condition is true. With the `||` operator the condition on the left has to be false for the interpreter to move on and evaluate the condition on the right. *If first condition is false then evaluate second condition. If left condition is true no need to evaluate right condition.* With Elvis operator you want to run the right hand condition if left condition is true. `&&` is closer to Elvis behavior. – 1.21 gigawatts Oct 17 '18 at 17:35

2 Answers2

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.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231
Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148
3

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

Ronen Cypis
  • 21,182
  • 1
  • 20
  • 25