简体   繁体   中英

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.

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.

rewrite it as

$.history.init(function(url) {
        if( url == ""){ 
           url = "#some-page";
         }
         load( url );
 });

Your rewritten code is invalid. Try this:

$.history.init(function(url) {
      if(url == "") {
         load("#some-page");
      } else {
         load(url);
      }
});

You need the if statement to be outside of the load function, ie

$.history.init(function(url) {
    if (url === "") { 
        url = "#some-page";
    }
    load(url);
});

Note that you don't need the else clause as url = url is a redundant operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM