Code Logo

Get Character with charAt()

Published at25 Jul 2026
JavaScript String Handling Easy 0 views
Like0

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

Example 1
Input
"hello",0
Output
"h"
Explanation

First character

Example 2
Input
"test",-1
Output
""
Explanation

Negative index returns empty string

Example 3
Input
"hello",1
Output
"e"
Explanation

Character at index 1

Example 4
Input
"hello",10
Output
""
Explanation

Out of bounds returns empty string

Example 5
Input
"abc",2
Output
"c"
Explanation

Last character

Algorithm Flow

Recommendation Algorithm Flow for Get Character with charAt()
Recommendation Algorithm Flow for Get Character with charAt()

Solution Approach

function solution(str, idx) {
  return str.charAt(idx);
}

Best Answers

javascript - Approach 1
function solution(str, idx) {
  return str.charAt(idx);
}