Convert all Array Elements to Uppercase in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 used the String.toUpperCase method to convert each 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. Declare a new variable and set it to an empty array.
  2. Use the forEach() method to iterate over the original array.
  3. Convert each string to uppercase and push the strings into the new 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.

Each element gets converted to uppercase and gets pushed into the new array.

Which approach you pick is a matter of personal preference. I prefer using the Array.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 have to perform some kind of mutation to persist the state.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.