Get Character with charAt()
Write a JavaScript function that takes a string and an index, and returns the character at that index using String.charAt(). If the index is out of range, return an empty string.
String.prototype.charAt() is a JavaScript method that returns the character at a specified index in a string. Unlike bracket notation (str[i]), charAt() returns an empty string for out-of-bounds indices instead of undefined. This makes it safer when the index might be outside the string's length.
The charAt() method treats characters as UTF-16 code units. For characters outside the Basic Multilingual Plane (like emoji), a single visual character may consist of two code units. charAt() returns the individual code unit, which may be half of a surrogate pair. For full Unicode support, use codePointAt() instead.
Time complexity is O(1) as charAt() simply reads from the internal character array. Space complexity is O(1). The method never throws an error for invalid indices; it gracefully returns an empty string.
Edge cases include negative indices (returns empty string), indices beyond string length (returns empty string), index 0 (returns first character), and very large indices (returns empty string without error).
Example Input & Output
First character
Negative index returns empty string
Character at index 1
Out of bounds returns empty string
Last character
Algorithm Flow
Solution Approach
Access a character at a specific index in a string using charAt(). This method returns the character at the given position. If the index is out of range, it returns an empty string. Unlike bracket notation str[i], charAt() works in older JavaScript engines.
charAt() is safer than bracket notation for out-of-bounds access: str[100] returns undefined, while str.charAt(100) returns ''.
Time O(1), Space O(1).
Best Answers
function solution(str, idx) {
return str.charAt(idx);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
