Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript ternary operator into full if/else statement issue

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.

like image 712
Iladarsda Avatar asked Jan 20 '26 22:01

Iladarsda


2 Answers

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.

like image 149
Tikhon Jelvis Avatar answered Jan 22 '26 11:01

Tikhon Jelvis


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.

like image 24
Alex Wayne Avatar answered Jan 22 '26 10:01

Alex Wayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!