First Letter of a String in JavaScript: test.CharAt() vs test[]
When we use a programming language everyday, now and then we find ourselves stumbling upon intricacies of that language that need some clarification. Today I encountered this as I was using JavaScript to convert an object to an XML string. While working through the object, there was a particular piece of the code that needed to evaluate the first character of a string. For those of you versed in JavaScript, you understand that there are actually a number of ways to accomplish this, most effectively by treating the string like an array [because JavaScript doesn't mind] or by using the handy charAt() function. Both seem to work fine… but what's the difference you might ask?
var test = 'string';
test[0];
// ---> returns "s"
var test = 'string';
test.charAt(0);
// ---> returns "s"
Doesn't seem to be a difference here. I was pretty stumped until my colleague, Nathan, suggested I try an invalid index.
var test = 'string';
test[5];
// ---> returns ""
var test = 'string';
test.charAt(5);
// ---> returns null
A-ha!
As you can see, charAt() returns a string regardless of the argument actually being a valid index or not. This is extremely useful in the case that you need the returned value to be a string for later usage.
Grabbing the value directly from the string as you would do with an array is also a useful technique if you need to know that it is indeed an invalid index.
Also, could one assume that comparing against null performs better than performing a string comparison?
Update: As it turns out, IE does not support the test[] method of accessing the value. It is advised that you always use test.CharAt().


May 26th, 2008 at 3:24 pm
This actually doesn't work in IE since I just ran into this bug.