Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Fabian Blank
To convert all array elements to uppercase:
map()
method to iterate over the array.toUpperCase()
method to convert the string to
uppercase and return the result.map
method will return a new array with all strings converted to
uppercase.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.
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:
forEach()
method to iterate over the original array.toUpperCase()
method and push it to the uppercase strings array.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.
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 need to declare a new variable
that will store the state from the operations we perform.
forEach
method is not supported in Internet Explorer. If you have to support the browser, use the map
approach instead.