Reputation: 31237
I was learning about javascript string methods here.
Under section Extracting String Characters, it said:
There are 2 safe methods for extracting string characters:
charAt(position)
charCodeAt(position)
The questions here are:
Upvotes: 1
Views: 1080
Reputation: 36703
There are two ways to access a character from a string.
// Bracket Notation
"Test String1"[6]
// Real Implementation
"Test String1".charAt(6)
It is a bad idea to use brackets, for these reasons (Source):
This notation does not work in IE7. The first code snippet will return undefined in IE7. If you happen to use the bracket notation for strings all over your code and you want to migrate to
.charAt(pos)
, this is a real pain: Brackets are used all over your code and there's no easy way to detect if that's for a string or an array/object.You can't set the character using this notation. As there is no warning of any kind, this is really confusing and frustrating. If you were using the
.charAt(pos)
function, you would not have been tempted to do it.
Also, it can produce unexpected results in edge cases
console.log('hello' [NaN]) // undefined
console.log('hello'.charAt(NaN)) // 'h'
console.log('hello' [true]) //undefined
console.log('hello'.charAt(true)) // 'e'
Basically, it's a short-cut notation that is not fully implemented across all browsers.
Note, you are not able to write characters using either method. However, that functionality is a bit easier to understand with the .charAt()
function which, in most languages, is a read-only function.
So for the compatibility purpose .charAt
is considered to be safe.
Speed Test: http://jsperf.com/string-charat-vs-bracket-notation
Testing in Chrome 47.0.2526.80 on Mac OS X 10.10.4
Test Ops/sec
String charAt
testCharAt("cat", 1);
117,553,733
±1.25%
fastest
String bracket notation
testBracketNotation("cat", 1);
118,251,955
±1.56%
fastest
Upvotes: 3