March 20, 2012
Check .length before applying substr()?
Question by Mike Hayes
In Javascript, is it better to do this:
var string = 'hello';
if(string.length > 10) {
string = string.substr(0,10);
}
or simply:
var string = 'hello';
string = string.substr(0,10);
I know the performance difference between the two won’t be anything huge but I like my JS to run as lightly as possible!
Which is the best to use?
Thanks
Answer by Starx
Or, may be you can combine both
var str = 'hello';
str = str.length > 10 ? str.substr(0,10) : str;