soren.qvist
soren.qvist

Reputation: 7416

Is there a way to simplify this javascript if-statement?

not an expert on js but this if-statement still tickles me because I suspect it can be written in a way more clever fashion:

if(event.value == "/")
{
    event.value = "/home";
}

Suggestions?

Upvotes: 0

Views: 285

Answers (6)

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

You can put it into function to make it look better.

function GetValue(s1, s2, s3) {
   return s1 == s2 ? s3 : s1;
}

...

event.value = GetValue(event.value, "/", "/home");

IMO it's useful only if you need it more than once.

Upvotes: 0

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

There isn't much more you can do with it really, other than Nick's suggestions, but here's another way to throw into the mix:

event.value += (event.value == "/") ? "home" : "";

Another, just for fun:

event.value = ((function(v){ return v=="/" ? v+'home' : v }(event.value))

Upvotes: 1

GolezTrol
GolezTrol

Reputation: 116190

I don't think there's a better way. You could omit the braces if your coding style guide allows you to, but it won't semantically make a difference. The shorter event.value = (event.value == '/')?'/home':event.value; is not so good, because it makes a useless assignment when the value differs from '/'.

Upvotes: 1

Pimgd
Pimgd

Reputation: 6043

if(event.value == "/"){
   event.value += "home";
}

Upvotes: 2

Marc B
Marc B

Reputation: 360892

event.value = (event.value == "/") ? "/home" : event.value;

would be about the only other practical option. The if() version is far more readable in this case.

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630627

You could omit the braces:

if(event.value == "/") event.value = "/home";

Or a conditional:

event.value = event.value == "/" ? "/home" : event.value;

...but I'm not sure either of those is really "better", and a with statement you should just stay away from.

Upvotes: 3

Related Questions