Convert all Array Elements to Uppercase in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Fabian Blank

Convert all Array Elements to Uppercase #

To convert all array elements to uppercase:

  1. Use the map() method to iterate over the array.
  2. On each iteration, call the toUpperCase() method to convert the string to uppercase and return the result.
  3. The map method will return a new array with all strings converted to uppercase.
index.js
const arr = ['apple', 'banana', 'cereal']; const upper = arr.map(element => { return element.toUpperCase(); }); // ๐Ÿ‘‡๏ธ ['APPLE', 'BANANA', 'CEREAL'] console.log(upper);

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 that contains all of the values we returned from the function.

We call the String.toUpperCase method on each iteration to convert the string to uppercase.

The map method returns a new array, it doesn't mutate the contents of the original array.

An alternative, but also very common approach is use the Array.forEach method.

To convert all array elements to uppercase:

  1. Create a variable that will store the uppercase strings and set it to an empty array.
  2. Use the forEach() method to iterate over the original array.
  3. On each iteration, convert the string to uppercase using the toUpperCase() method and push it to the uppercase strings array.
index.js
const arr = ['apple', 'banana', 'cereal']; const upper = []; arr.forEach(element => { upper.push(element.toUpperCase()); }); // ๐Ÿ‘‡๏ธ ['APPLE', 'BANANA', 'CEREAL'] console.log(upper);

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

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

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

The forEach method returns undefined, so we need to declare a new variable that will store the state from the operations we perform.

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