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;

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!