Jack Shephard
Jack Shephard

Reputation: 13

Using ternary in JavaScript

Is there a shorter way to write this?

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

Upvotes: 1

Views: 142

Answers (5)

fantactuka
fantactuka

Reputation: 3334

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

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

Upvotes: 0

Mic
Mic

Reputation: 25154

Another option is to use a regex:

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

But then you have 2 problems :)

Upvotes: 1

Davy Meers
Davy Meers

Reputation: 1798

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"

Upvotes: 2

Daniel Vassallo
Daniel Vassallo

Reputation: 344301

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.

Upvotes: 3

Antares
Antares

Reputation: 285

Or :

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

Upvotes: 0

Related Questions