Convert All Array Elements To Uppercase

To convert all array elements to uppercase, you can use any of these methods –

  1. Use the Array.map() method to iterate over the array and convert each element to uppercase.
  2. Use the Array.forEach() method to iterate over the array and push each element to a new array after converting it to uppercase.

Let’s discuss each of these methods in detail below.

convert all array elements to uppercase in JavaScript

1. Array.map() To Convert All Array Elements To Uppercase

The map() method creates a new array with the results of calling a function for every element in the array. In our case, we can use this method to convert each element in the array to uppercase. See the example below:

var arr = ["a", "b", "c"];

var newArr = arr.map(function(element) { 

 return element.toUpperCase(); 

});

console.log(newArr);

// Output: ["A", "B", "C"]

In the above code, we have created an array with three elements – “a”, “b”, and “c”. We have then used the map() method to convert each element in the array to uppercase. Finally, we have logged the new array to the console.

2. Array.forEach() To Convert All Array Elements To Uppercase

The forEach() method executes a provided function once for each array element. In our case, we can use this method to convert each element in the array to uppercase and push it to a new array. See the example below:

var arr = ["a", "b", "c"];

var newArr = [];

arr.forEach(function(element) { 

 newArr.push(element.toUpperCase()); 

});

console.log(newArr);

// Output: ["A", "B", "C"]

In the above code, we have again created an array with three elements – “a”, “b”, and “c”. We have then created an empty array – newArr. We have used the forEach() method to convert each element in the array to uppercase and push it to the new array. Finally, we have logged the new array to the console.

Thus, using either of the above methods, you can easily convert all array elements to uppercase. Do let me know if you have any doubts or queries in the comments section below.

Leave a Reply