Player_50B
Player_50B

Reputation: 99

String.charAt() vs String.at()

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.

Upvotes: 7

Views: 4120

Answers (3)

Shahadat Shemul
Shahadat Shemul

Reputation: 21

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

Upvotes: 2

Addition to Shahadat Shemul's answer:

  • ''.at(nonExistentPosition) === undefined
  • ''.charAt(nonExistentPosition) === ''

Upvotes: 3

Pavel Savva
Pavel Savva

Reputation: 529

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.

Upvotes: 11

Related Questions