Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
To convert all array elements to lowercase:
map()
method to iterate over the array.toLowerCase()
method to convert the string to
lowercase and return the result.map
method will return a new array containing only lowercase strings.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 used the String.toLowerCase method to convert each string in the array to lowercase.
map()
method returns a new array, it doesn't change the original array.An alternative, but also very commonly approach is to do this using the Array.forEach method.
To convert all array elements to lowercase:
forEach()
method to iterate over the original array.const arr = ['ONE', 'TWO', 'THREE']; const lower = []; arr.forEach(element => { lower.push(element.toLowerCase()); }); console.log(lower); // 👉️ ['one', 'two', 'three']
We used the Array.forEach method to convert all array elements to lowercase.
The function we passed to the forEach()
method gets called with each element
in the array.
Each element gets converted to lowercase and gets pushed into the new array.
This approach is a bit more manual and verbose. It's very similar to using a
for
loop.
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.