What is charAt() Javascript String prototype?šŸ˜±

Nk Rafi
1 min readMay 7, 2021

--

Similar to all programming languages there is a data type called ā€œstringā€. In this string data type, there is some prototype available. From all of this string prototype, the charAt() is one of the important. Then what does this prototype do?

carAt() is a method for string, which uses to get the individual character from a string which is in a form of a sentence. Let's take a look at an example code for better understanding.

let myString = ā€œhello there, Iā€™m a stringā€;
console.log(myString.charAt(0))
#output:
"h"

To get an individual character in a string you have to pass the index of the character in a string, as an argument of the method charAt(). In our case for the character ā€œhā€, the index of the ā€œhā€ is 0 in the myString variable.

Return Values of charAt():

Agin if you want a character you need to pass the index of that character in a string, as an argument of the method charAt(). If you donā€™t pass any argument the charAt() method will set the argument as index 0 which will return the first character in a string. If you pass an index that is out of the range of the stringā€™s last index in that case, it will return an empty string. Letā€™s look at some example:

var myString2 = 'hello world';
console.log("The character at index 0 is '" + anyString.charAt() + "'");
// No index was provided, used 0 as default

console.log(myString2.charAt(0))
console.log(myString2.charAt(1))
console.log(myString2.charAt(2))
console.log(myString2.charAt(3))
console.log(myString2.charAt(5))
console.log(myString2.charAt(500))
#output:
"h"
"e"
"l"
"l"
"o"
""

--

--

Nk Rafi
Nk Rafi

Written by Nk Rafi

0 Followers

Tech writer. Bridging complex tech and plain language. Passionate about innovation. Educating and inspiring readers to stay ahead.

No responses yet