1

Is there a shorter way to write this?

var ttt = "dd";
if (ttt.length < 3) 
ttt= "i" + ttt;
3
  • It would pay to note that all the answers here are longer and less obvious than the original code. While it can be done, I definitely wouldn't suggest you do (for the sake of those reading the code later). Commented Aug 19, 2010 at 11:16
  • @Aidan: i cannot see how "var ttt="idd";" is longer and less obvious... . Commented Aug 19, 2010 at 11:29
  • @davyM... I'll give you that one but only on a literal level. Commented Aug 19, 2010 at 16:41

5 Answers 5

3

Yours is pretty short, but if you want to use the the conditional operator (a.k.a the ternary operator), you could do the following:

var ttt = "dd";
ttt = ttt.length < 3 ? "i" + ttt : ttt;

... or if bytes are really precious (code golfing?), you could also do something like this:

var ttt = "dd".length < 3 ? "i" + "dd" : "dd";

... but then that could be reduced to just:

var ttt = "idd";

... as @Nick Craver suggested in a comment below.

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

3 Comments

+1 - I dunno though....var ttt = "idd"; seems pretty short ;) Also, you need quotes around the i to be 100% on this one ;)
@Nick Fixed: Thought it was a variable at first.
A+++++++ would do business again
2

The shortest with the same result is:

var ttt="idd";

because "dd" has a length of 2. so the if is always true and you'll always prepend "i"

Comments

1

Another option is to use a regex:

var ttt = "dd".replace(/^(\w?\w?)$/, 'i$1');

But then you have 2 problems :)

Comments

0

Or :

var ttt = "dd";
ttt = (ttt.length < 3 ? i : "") + ttt;

Comments

0

Also there's a way with && operator instead of if

var ttt = "dd";
ttt.length < 3 && (ttt = "i" + ttt);

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.