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

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'];

How Recursion Works Here

The recursive function processes one array element at a time, capitalizes it, then calls itself with the next index until all elements are processed.

Example

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);
    };
    return;
};

capitalize(arr);
console.log(arr);

Output

And the output in the console will be −

[ 'Apple', 'Banana', 'Orange', 'Grapes' ]

Key Points

  • The function modifies the original array in-place using recursion

  • Base case: when index reaches array length, recursion stops

  • Helper function handles the capitalization logic for each string

  • Each recursive call processes the next array element

Conclusion

This recursive approach efficiently capitalizes array elements without extra memory allocation. The function modifies the original array in-place, making it memory-efficient for large datasets.

Updated on: 2026-03-15T23:19:00+05:30

466 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements