I have following ternary statement:
$.history.init(function(url) {
load(url == "" ? "#some-page" : url);
});
Which I have rewrote into:
$.history.init(function(url) {
load(
if( url == ""){ url = "#some-page"
} else { url = url }
);
});
I now the is an error on line 3 if(url == ""), but I don’t understand what error.
Any suggestion much appreciated.
In JavaScript, an
ifis not an expression. It does not return a value and cannot be put inside a function call. That is, this is not valid:This is the main difference between
ifand?:–the operator is an expression and returns a value;ifis a statement, does not return a value and cannot be used everywhere.Your best bet if you have to avoid the ternary operator is to do something like:
You can also achieve the same effect using
||:This is the shortest and most idiomatic way to write your code.