JavaScript String charAt()

The JavaScript String charAt() method returns the character at the specified index in a string.

The syntax of the charAt() method is:


Here, str is a string.

charAt() Parameters

The charAt() method takes in :

  • index - An integer between 0 and str.length - 1. If index cannot be converted to integer or is not provided, the default value 0 is used.

Return value from charAt()

  • Returns a string representing the character (exactly one UTF-16 code unit) at the specified index.

Note: charAt() returns an empty string if index is out of range.

Example: Using charAt() method

let sentence = "Happy Birthday to you!";

let index1 = sentence.charAt(2);
console.log("Character at index 2:" + index1); // 'p'

// index is converted to integer
let index2 = sentence.charAt(6.5); // 'B'
console.log("Character at index 6:" + index2);

// Empty string if index out of range
let index3 = sentence.charAt(100);
console.log("Character at index 100:" + index3); // ''

// default value is 0
let index4 = sentence.charAt();
console.log("Character at index 0:" + index4); // 'H'


Character at index 2: p
Character at index 6: B
Character at index 100: 
Character at index 0: H

Recommended Reading: JavaScript String charCodeAt()

Did you find this article helpful?