JavaScript String charAt Method

JavaScript String charAt Method

Sometimes, we need to get some character at the given index, from the string. In such situations, we can make use of the charAt method. This method is simple to use and understand. This method takes the given index as an argument and then returns the character at the given index in the string.

JavaScript String charAt Method

The thing is that there is nothing like character type in JavaScript. The returned thing is going to be some string only.

So, in short, the charAt method takes some index as an argument and returns the character at the given index. Let’s have a look at an example, which highlights the use of the charAt method –

Get the first character of string javascript

You can see in the above program, that there is a string, and we are calling the charAt method on the string. This method returns the character at the specified index. Have a look at the output for the above program –

As you can see, in the output, we get the character at the given index in the string. You can try using the charAt method too, for practice, and getting familiar with the method. Now, there might be a question, what if we give such an index, which is out of bounds for the string? Well, this is a situation, where we are trying to get a character at such an index, which is not there.

What can we expect to get in such a situation? Well, the simple answer to this question, is an empty string. You can try giving some index, which is out of bounds for the given string.

Also, you can try giving no argument at all, to the charAt method. In such a situation, when there is no argument given to the charAt method, the default argument is considered to be 0.

So, these are some of the methods, which can be a lot of help, for doing different things, with the strings, like converting the string to uppercase, or lowercase, getting some substring, and a lot more. You can try these methods, with a lot of examples, so that you can become familiar with all those methods, and use them whenever required.