Difference Between Str[0] And Str.charAt(0)
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
Solution 1:
[]
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 ""
Solution 2:
This
""[-4] // undefined
"".charAt(-4) // ""
You could ensure that the result would be a string.
Post a Comment for "Difference Between Str[0] And Str.charAt(0)"