String.charAt() vs String.at()
Asked Answered
R

3

5

What is the difference between the "String.charAt()" method and the "String.at()" method?

I tried to understand how they work, but other than the fact that the "at" method can have a negative value, I did not find any more.

Reachmedown answered 21/3, 2023 at 23:49 Comment(6)
Link to the pair of documentation URLs you’re relying on, please.Foison
The fact that .at() understands a negative index is the only difference.Pricket
Did you look up the docs for the two functions? What did it tell you?Ironworker
charAt has also been supported far longer.Letishaletitia
@Pricket plus the part where .at() also works for arrays, giving you one function for doing "the same thing" to both arrays and strings (which already supported array notation for accessing letters the same way you would array elements).Ironworker
@Mike'Pomax'Kamermans OK sure, that's a thing, but this question isn't taking that into account I don't think. Still it's a very good point.Pricket
C
9

at() is a newer addition to JavaScript compared to charAt(). According to MDN, both charAt() and at() are valid, but at() is more "succinct and readable". The ability to use negative indexes makes your code more concise since you can do things like myString.at(-2) instead of myString.charAt(myString.length - 2).

charAt() has better support of older browser versions (1, 2), but I would give that absolutely no consideration, unless you have an extremely specific use case.

Ciao answered 22/3, 2023 at 0:1 Comment(0)
H
2

at()

  • is newer (supported by all browsers only since March 2022)
  • works with any iterable object
  • accepts negative values as arguments
  • returns undefined if we pass a number as an argument that is >= the length of the string

charAt()

  • is older and as such supported by older browser versions
  • only works with strings
  • doesn't accept negative values as arguments
  • returns empty string '' if we pass a number as an argument that is >= the length of the string
Hemistich answered 15/11, 2023 at 2:9 Comment(0)
G
2

Addition to Shahadat Shemul's answer:

  • ''.at(nonExistentPosition) === undefined
  • ''.charAt(nonExistentPosition) === ''
Gringo answered 8/4 at 10:14 Comment(3)
Hi! If this is just an improvement to an existing answer, you can suggest an edit to it to improve what we have, instead of having multiple scattered posts. Thanks for helping!Facilitation
@DarrylNoakes: a question: Does a brand-new user have the ability to edit another's post? (It's been a long time!) I know that one needs 50 rep to comment on others, and 2000 to edit without necessarily requiring review. But I don't know about offering suggested edits.Burgh
@ScottSauyet True, I can't remember if there is a rep requirement for suggesting edits. But I can't find a "suggest edits" privilege in the list, so I'm assuming you can from the start.Facilitation

© 2022 - 2024 — McMap. All rights reserved.