0

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?

2
  • 1
    What is it about the statement that you don't like? I mean, as statements go, that's pretty short already. Commented Dec 13, 2010 at 20:43
  • I came in here expecting a logic problem... this is a white-space problem. Commented Dec 13, 2010 at 20:47

6 Answers 6

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Fast as always :) So that's basically like PHP I guess. Is there a shorter way to refer to event.value 'within' the brackets? Like: if(event.value == "/") sameval = "/home";
@soren.qvist - There is, the with statement I liked above, but it's evil for a few reasons - and not available in all browsers.
1
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.

Comments

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

1 Comment

Nice one, 1 less character to type. :)
1

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 '/'.

Comments

1

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))

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.