What's the difference between .substr(0,1) or .charAt(0)?
Measuring it is the key!
Go to http://jsperf.com/substr-or-charat to benchmark it yourself.
substr(0,1) runs at 21,100,301 operations per second on my machine, charAt(0) runs 550,852,974 times per second.
I suspect that charAt accesses the string as an array internally, rather than splitting the string.
As found in the comments, accessing the char directly using string[0] is slightly faster than using charAt(0).
Unless your whole script is based on the need for doing fast string manipulation, I wouldn't worry about the performance aspect at all. I'd use charAt()
on the grounds that it's readable and the most specific tool for the job provided by the language. Also, substr()
is not strictly standard, and while it's very unlikely any new ECMAScript implementation would omit it, it could happen. The standards-based alternatives to str.charAt(0)
are str.substring(0, 1)
and str.slice(0, 1)
, and for ECMAScript 5 implementations, str[0]
.