Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extended Ternary expression

I know you can do ternary expressions in Javascript for an if - else statement, but how about an else- else if- else statement? I thought that surely this would be supported but I haven't been able to find any info about it and wasn't able to get it to work just hacking around.

like image 339
user3619165 Avatar asked May 27 '26 08:05

user3619165


2 Answers

In contrast to Robby Cornelissen's answer - there is no problems with readability if you format it properly (and not writing PHP, since it messed up the operator by making it left-associative in contrast to all other languages that have that construct):

var y =
  x == 0 ? "zero" :
  x == 1 ? "one" :
  "other";

EDIT

What I was looking for is a shorter version of "if expression 1 is true, return expression 1. Else if expression 2 is true, return expression 2. Else return expression 3". Is there no clean way to do this?

There is: expression1 || expression2 || expression3. (It would have been nice if you had put this into your question in the first place.) This is commonly used for default values:

var defaults = null;
function hello(name) {
  var displayName = name || (defaults && defaults.name) || "Anonymous";
  console.log("Hello, " + displayName + ".");
}

hello("George");
// => Hello, George.
hello();
// => Hello, Anonymous.
defaults = {};
hello();
// => Hello, Anonymous.
defaults.name = "You"
hello();
// => Hello, You.

However, it is important to be aware of the conditions for truthiness. For example, if you expect "" or 0 to be a valid value that does not need to be replaced by a default, the code will fail; this trick only works when the set of possible non-default values is exactly the set of truthy values, no more and no less. E.g.

function increment(val, by) {
    return val + (by || 1);      // BUG
}

increment(10, 4);
// => 14
increment(10, 1);
// => 11
increment(10);
// => 11
increment(10, 0);
// => 11                         <-- should be 10

In this case you need to be explicit:

function increment(val, by) {
    return val + (typeof(by) === "undefined" ? 1 : by);
}
like image 156
Amadan Avatar answered May 31 '26 23:05

Amadan


I wouldn't recommend it because of readability, but you could just nest ternary operators:

var y = (x == 0 ? "zero" : (x == 1 ? "one" : "other"));

This would be the equivalent of:

var y;

if (x == 0) {
    y = "zero";
} else if (x == 1) {
    y = "one";
} else {
    y = "other";
}
like image 31
Robby Cornelissen Avatar answered Jun 01 '26 00:06

Robby Cornelissen