Convert all Array Elements to Lowercase in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Cole Patrick

Convert all Array Elements to Lowercase #

To convert all array elements to lowercase:

  1. Use the map() method to iterate over the array.
  2. On each iteration, call the toLowerCase() method to convert the string to lowercase and return the result.
  3. The map method will return a new array containing only lowercase strings.
index.js
const arr = ['ONE', 'TWO', 'THREE']; const lower = arr.map(element => { return element.toLowerCase(); }); console.log(lower); // ๐Ÿ‘‰๏ธ ['one', 'two', 'three']

The function we passed to the Array.map method gets called with each element (string) in the array.

The map method returns a new array containing all the values the callback function returned.

We call the String.toLowerCase method on each iteration to convert the string to lowercase.

The map method returns a new array, it doesn't change the original array.

An alternative, but also very common approach is to do this using the Array.forEach method.

To convert all array elements to lowercase:

  1. Declare a variable that will store the lowercase strings and set it to an empty array.
  2. Use the forEach() method to iterate over the original array.
  3. On each iteration, push the result of calling the toLowerCase() method on the string into the lowercase strings array.
index.js
const arr = ['ONE', 'TWO', 'THREE']; const lower = []; arr.forEach(element => { lower.push(element.toLowerCase()); }); console.log(lower); // ๐Ÿ‘‰๏ธ ['one', 'two', 'three']

We achieved the same result, however this time we used the Array.forEach method.

The function we passed to the forEach method gets called with each element in the array.

We lowercase each element and push it into the new array.

This approach is a bit more manual and verbose, however it's very similar to using a for loop.

Which approach you choose is a matter of personal preference. I prefer the mapmethod, because it returns a new array and we don't have to declare an intermediary variable.

The forEach method returns undefined, so we have to perform some kind of mutation to persist the state.

The forEach method is not supported in Internet Explorer. If you have to support the browser, use the map approach instead.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee