JavaScript charAt

The charAt() methods is helpful to get the specific character from the string. If you want any single and specific character from the string so you can use the charAt() method.




An integer between 0 and 1 minus from the length of the string.

Return type:

JavaScript does not have the character data type.  So charAt() methods return the string and that is sub-string of the original string.

var yourString = "JavaScript Hive";
document.writeln(typeof yourString.charAt(0)); // returns the "string"


Here we have to pass the index of the character so index start with always 0 and up to less than 1 from the length of the string. So you have to pass the value between 0 to string length – 1. If you pass the argument less than 0 or greater that string length – 1 than charAt() method returns the nothing or null or empty string.


var yourString = "JavaScript Hive";
document.writeln(yourString.charAt(0) + yourString.charAt(1) + yourString.charAt(2) + yourString.charAt(3));
//It will print the "Java" on the screen.

string.charAt(index) or string[index]:

var yourString = "JavaScript Hive";
document.writeln(yourString[0]); //First method
document.writeln(yourString.charAt(0)); //Second method

The first method is short-hand method of the charAt() method, which is not full-implemented all the browsers mostly on the old browser like IE6, IE7. The first method was introduce in the ECMAScript 5 so it’s difficult to you handle the operation on the old browser.

JavaScript does not allowed you to change the string. So there is no sense to use the First method (notation method) and the charAt() method is good and read only method that you can find in many programming languages.

I recommend to you use the charAt() method, If in future you have to provide the old browser support so its become the panic and headache to go and change the notation to the charAt() method.

Magic of the charAt():

Magic of the charAt() method that does not available to the notation method. Because the charAt() methods depends on the how the index or argument passed to the method is converted to the number.

var yourString = "JavaScript Hive";
document.writeln(yourString[NaN]); // returns the undefined.
document.writeln(yourString.charAt(NaN)); // returns the J

document.writeln(yourString[true]); // returns the undefined.
document.writeln(yourString.charAt(true)); // returns the a

If you use the notation than you must be pass the valid index of it which is available to the string. In charAt() if you pass the invalid index than it returns the empty string, where the notation will returns the “undefined” message which is not looks which you code the long program.

So it’s highly recommended to use the charAt() method.

Happy Coding!!!