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 if is not an expression. It does not return a value and cannot be put inside a function call. That is, this is not valid:
func(if (a) { ... } else { ... });
This is the main difference between if and ?:--the operator is an expression and returns a value; if is 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:
if (url == "") {
url = "#some-page";
}
load(url);
You can also achieve the same effect using ||:
function (url) {
load(url || "#some-page");
}
This is the shortest and most idiomatic way to write your code.
if expressions dont return anything in JS. So that basically does load(undefined).
Try this instead:
if (url === '') {
url = '#some-page';
}
load(url);
Note you don't need to else at all, because if the value is present you have nothing to change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With