Is there a shorter way to write this?
var ttt = "dd";
if (ttt.length < 3)
ttt= "i" + ttt;
Is there a shorter way to write this?
var ttt = "dd";
if (ttt.length < 3)
ttt= "i" + ttt;
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.
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"
Another option is to use a regex:
var ttt = "dd".replace(/^(\w?\w?)$/, 'i$1');
But then you have 2 problems :)
Also there's a way with && operator instead of if
var ttt = "dd";
ttt.length < 3 && (ttt = "i" + ttt);