How can I use charAt()?

Follow-up question here. Has anyone tried employing .charAt() which is given as alternate method in hint #2?

I’m probably doing things wrong, but it doesn’t seem to be recognizing .charAt().

const animals = [‘hippo’, ‘tiger’, ‘lion’, ‘seal’, ‘cheetah’, ‘monkey’, ‘salamander’, ‘elephant’];

const startsWithS = animals.charAt(letter => {
  return letter[0] ===  XXXX

I didn’t finish the code block (hence the gibberish) because regardless of what I put in, it didn’t get past the fact that it wasn’t recognizing .charAt(). I’m getting the error:

const startsWithS2 = animals.charAt(letter => {

TypeError: animals.charAt is not a function
    at Object.<anonymous> (/home/ccuser/workspace/javascript-iterators-find-index/main.js:12:30)

Any ideas? Am I missing something obvious?

The String.charAt() method does not take a callback. It takes an index.

"string".charAt(0) === 's'   // true

Now we could use this as the function body of a filter callback…

startsWithS = animals.filter(x => x.charAt(0) === 's');

Thank you so much for the reply and the time taken! I didn’t even consider that. It’s hard to step back and consider larger scale mistakes or assumptions you are making when you’re quite caught up in a flawed assumption.

1 Like

Don’t I know that. It can be embarrassing to be so far out in left field only to be pulled back in with a simple explanation of where we are wrong. I blush at least once a day.

It’s no sin to be wrong, and should not hold us back so long as we own it and are willing to take criticism and correction. Personally, I depend upon it.


I’m taking advantage of the being wrong a lot, and am always happy to be corrected and shown things.

I find that I’m running into the problem of having difficulty understanding different-than-I’m-used-to syntax (I assume this is normal at my early stage). For example, I used your code block:

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
startsWithS = animals.filter(x => x.charAt(0) === 's');

And this returned [seal, salamander] which is great – but now I’m running into the problem of not knowing how to modify the code to make it select the first index that starts with ‘s’, and only that first index. What would be the way to make it return the singular value (in this case, seal) instead?

1 Like

Consider findIndex.

a = animals.findIndex(x => x.charAt(0) === 's')
// <- 3
b = animals[a]
// <- "seal"
const startsWithS = animals.findIndex(animal => {
 return animal.charAt === "s"  true:false

I ppased with this code but got an error, when I removed “true:false” , i still passed and the error left. What does true:false mean

In the present context, it means nothing. As superfluous code it can/should be removed.

We can rewrite your code to remove the braces and the return keyword…

const startsWithS = animals.findIndex(animal => animal.charAt(0) === 's');

Note the index as an argument to charAt.

1 Like