Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between str[0] and str.charAt(0) [duplicate]

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?

like image 726
kfasny Avatar asked Mar 29 '14 08:03

kfasny


2 Answers

[] 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 ""

like image 62
Amit Joki Avatar answered Sep 21 '22 23:09

Amit Joki


This

""[-4]          // undefined

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

You could ensure that the result would be a string.

like image 45
loxxy Avatar answered Sep 23 '22 23:09

loxxy