Iladarsda
Iladarsda

Reputation: 10696

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.

Upvotes: 3

Views: 841

Answers (5)

Alex Wayne
Alex Wayne

Reputation: 187014

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.

Upvotes: 1

jabclab
jabclab

Reputation: 15042

You need the if statement to be outside of the load function, i.e.

$.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.

Upvotes: 0

Konrad Dzwinel
Konrad Dzwinel

Reputation: 37903

Your rewritten code is invalid. Try this:

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

Upvotes: 0

Dau
Dau

Reputation: 8848

rewrite it as

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

Upvotes: 0

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68152

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.

Upvotes: 6

Related Questions