Capitalize the first letter ES6 solution

I found here this code:

const capitalize = ([firstLetter, ...restOfWord]) =>
  firstLetter.toUpperCase() + restOfWord.join('')

But only works for one word. I’d like to make it work for a sentence; e.g. “I’m a little teapot”.

I can’t figure out how to use a loop with array destructuring.

One possibility would be to rewrite that function to a version that you do understand, and then implement it in your loop.

So? Can someone explain to me how to do this?


1 Like

@ShaCP Yeah that’s a solution, but it doesn’t help the OP to adjust their own code. If they only wanted to copy/paste some solution, they could’ve gotten that from the hints page.

@Porphyrogennitos Can you be more specific about what confuses you concerning destructuring? Maybe this clears it up a little:

const capitalize = (string) => {
    const [firstLetter, ...restOfWord] = string;
    return firstLetter.toUpperCase() + restOfWord.join('')
1 Like

I understood destructuring but I couldn’t think of how to implement it with a loop.

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

The problem wasn’t really destructuring. It was how to implement it with a loop. My code explains that. It’s pretty self-explanatory.

When in doubt, I always recommend writing a simple, dumb loop to do the task before adding fancy syntax. Anything you can do with advanced syntax can also be done with basic syntax.

In this case, it is a question of what you want to loop over. You want to capitalize every word in a sentence, so it feels natural to me to loop over every word. Then I’d ask myself

  1. How do you get every word from a sentence?
  2. What do you want to do to every word?
  3. How do I join those modified words back together?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.