JavaScript Fundamentals

Efficiently Getting the Last Character of a String in JavaScript

Spread the love

JavaScript provides several efficient ways to retrieve the final character of a string. This article explores four common methods, comparing their readability and performance to help you select the optimal approach for your coding needs.

Table of Contents

Using charAt()

The charAt() method offers a straightforward and efficient solution. It takes an index as input and returns the character at that specific position. To access the last character, we subtract 1 from the string’s length to get the correct index.


let myString = "Hello World!";
let lastChar = myString.charAt(myString.length - 1);
console.log(lastChar); // Output: !

Using slice()

The slice() method provides a concise alternative. By passing -1 as the starting index (which counts from the end), it extracts the last character.


let myString = "Hello World!";
let lastChar = myString.slice(-1);
console.log(lastChar); // Output: !

slice() is generally preferred over substr() due to its better browser compatibility and clearer semantics.

Using substr()

The substr() method also supports negative indices. Similar to slice(), a negative starting index of -1 along with a length of 1 retrieves the last character. However, substr() is considered a legacy method and is less preferred than slice().


let myString = "Hello World!";
let lastChar = myString.substr(-1, 1); //Note the length argument is needed
console.log(lastChar); // Output: !

Best Practices and Recommendations

For extracting the last character of a string in JavaScript, charAt(string.length -1) and slice(-1) are the recommended approaches. They are both efficient, readable, and widely supported across all modern browsers. Avoid using substr() due to its legacy status. Avoid unnecessarily complex methods like splitting the string into an array unless you have other reasons to do so, as this significantly impacts performance.

Leave a Reply

Your email address will not be published. Required fields are marked *