What is the difference between the following two functions?
let str = 'hello world';
str.at(6) // w
str.charAt(6) // w
The only difference that I can find in the documentation is that .at()
accepted negative indices, is there another difference?
2
Answers
Both methods will return a new string consisting of a single UTF-16 encoded character located at the specified offset o the string.
The difference is that
.at
accepts negative numbers, and it is a much newer feature, so older versions of some engines might not support it.Another difference is the default value returned if the number provided as a parameter exceeds the length of the string.
.at
will returnundefined
while.charAt
will return an empty string.You can find more information here (.at()) and here (.charAt())
There are few things I can recall:
at()
is newerat()
returnsundefined
andcharAt()
returns an empty string