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"
""