skip to Main Content

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


  1. 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 return undefined while .charAt will return an empty string.

    You can find more information here (.at()) and here (.charAt())

    Login or Signup to reply.
  2. There are few things I can recall:

    • obviously browser support, at() is newer
    • when out of range, at() returns undefined and charAt() returns an empty string
    • negative indices (already mentioned by you)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search