5

What is the difference between str[0] and str.charAt(0)? I always access specific character by simply typing str[i], where i is the index of the character I want to access (counted from 0), but last week I had good overview of open source JS code, and in every single project I saw, people use charAt method.

Is there any difference between those two ways?

GSerg
  • 76,472
  • 17
  • 159
  • 346
kfasny
  • 235
  • 1
  • 3
  • 8
  • String 101 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String – Prasanth Mar 29 '14 at 08:47

2 Answers2

6

[] is a more primitive way of accessing all kind of arrays.

charAt() is specific to strings.

You can access the index of any array by using [], but you can only use charAt() on a string.

But when it comes to string alone, both are one and the same.

But you should use charAt() because, it is well supported in all the major browsers, while the bracket notation will return undefined in IE7

Also, the bracket notation is simply accessed, while charAt() does some validation and doesn't return undefined, but will return an empty string ""

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
4

This

""[-4]          // undefined

"".charAt(-4)   // ""

You could ensure that the result would be a string.

loxxy
  • 12,990
  • 2
  • 25
  • 56