Get the last Character of a String in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 07 20211 min read

Get the last Character of a String #

To get the last character of a string, call the charAt() method on the string, passing it the last index as a parameter. For example, str.charAt(str.length - 1) returns a new string containing the last character of the string.

index.js
const str = 'abcde'; const last = str.charAt(str.length - 1); console.log(last); // ๐Ÿ‘‰๏ธ e

The parameter we passed to the String.charAt method is the index.

Indexes are zero-based in JavaScript. The first character in the string has an index of 0, so the last character in the string has an index of str.length - 1.

If pass an index that does not exist on the string, the charAt method returns an empty string.

index.js
const str = ''; const last = str.charAt(str.length - 1); console.log(last); // ๐Ÿ‘‰๏ธ ""

An alternative approach is to directly access the index on the string.

To get the last character of a string, access the string at the last index, using bracket notation. For example str[str.length - 1] returns the last character in the string.

index.js
const str = 'abcde'; const last = str[str.length - 1]; console.log(last); // ๐Ÿ‘‰๏ธ e

Accessing the character at the last index achieves the same result as the charAt method.

However, if we try to access a character at an index that doesn't exist, we get undefined back.

index.js
const str = ''; const last = str[str.length - 1]; console.log(last); // ๐Ÿ‘‰๏ธ undefined
This is the main reason I prefer the `charAt` method, which would return an empty string at this case.

It's always easier to reason about and manage an application if we're consistent with types.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee