Using a recursive function to capitalize each word in an array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of String literals. The function should do the following two things −

  • Make use of recursive approach

  • Make first word of each string element capital.

Our function should do this without using extra space for storing another array.

For example −

If the input array is −

const arr = ['apple', 'banana', 'orange', 'grapes'];

Then the array should be transformed to −

const output = ['Apple', 'Banana', 'Orange', 'Grapes'];


The code for this will be −

const arr = ['apple', 'banana', 'orange', 'grapes'];
const capitalize = (arr = [], ind = 0) => {
   const helper = (str = '') => {
      return str[0].toUpperCase() + str.slice(1).toLowerCase();
   if(ind < arr.length){
      arr[ind] = helper(arr[ind]);
      return capitalize(arr, ind + 1);


And the output in the console will be −

[ 'Apple', 'Banana', 'Orange', 'Grapes' ]
Published on 23-Nov-2020 11:26:37