0

I've tried to search over SE without great success, however link me to the right topic if I'm wrong.
What I'd like to achieve is use a shortcut of JS's ternary operator, let me explain myself :
In PHP, you can do something like

<?php 
    $var1 = "1"; //example
    $var2 = ($var1) ?: "2";
    echo $var2 //echoes "1";
?>

as you can see/may already know, ?: returns $var1 when if evaluates to "true" (in this case !empty($var1), or "2" otherwise.
Now my question is, is there a way do achieve the same thing in Javascript?

Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
Julien Lachal
  • 1,101
  • 14
  • 23
  • A shortcut for an operator that is already a shorthand for an if / else statement? – GolezTrol Aug 05 '14 at 12:43
  • Yes, and [the syntax is identical](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)! You could have just tried it. – Quentin Aug 05 '14 at 12:44
  • Actually it would have been hard to ignore SE's suggestions when asking – mplungjan Aug 05 '14 at 12:45
  • 1
    @mplungjan - The proper duplicate is http://stackoverflow.com/questions/2932754/ternary-operators-in-javascript-without-an-else and not the linked question. – eb80 Aug 05 '14 at 12:46
  • 2
    Please read the question before swinging Mjölnir, so that you might mark as the *right* duplicate. – Niet the Dark Absol Aug 05 '14 at 12:47
  • 1
    People need to read the question; `?:` is not a valid javascript operator token as it is in PHP – Alex K. Aug 05 '14 at 12:47
  • I can't really see why I got downvoted here ... as I didn't know how to use it, I couldn't have known about the || operator ... whatever. – Julien Lachal Aug 05 '14 at 13:01
  • as I explained in the note that was deleted by an edit, I had no way of searching for || because I didn't know what to look for, if you know what I mean. – Julien Lachal Aug 05 '14 at 15:50

0 Answers0