What is the difference between arr[i]
and arr.charAt(i)
?
the second one is not valid syntax
how about now? what is the difference
there are small differences, like what happens if the index is out of boundaries, but not much
performance-wise I have no idea
.charAt()
can only be used on strings, not arrays.
But referencing an index in brackets can be done on both strings and arrays.
EXAMPLES:
str = "the lazy dog"
str.charAt(4) ==> "l"
str[4] ==> "l"
arr=["a", "b", "c", "d"]
arr[2] ==> "c"
arr.charAt(2) ==> Uncaught TypeError: arr.charAt is not a function at <anonymous>:1:5
charAt
was part of the language long before you could access characters in string using the bracket notation, and to keep backwards compatibility it won’t ever be removed. It’s how you accessed a character at a specific index in a string, you couldn’t do anything else.
It doesn’t quite work the same way – it converts whatever you give it to an integer, so if you do like "abc".charAt(2.1)"
or "abc".charAt(true)"
or "abc".charAt(null)"
it’ll work rather than erroring (2.1 will be 2, true will be 1, null will be 0). It has no real advantages though, just use the bracket notation unless you need to do something really weird like support twenty-year-old browsers