How to Convert Array to Uppercase in Javascript
In this tutorial, you will learn how to convert array to uppercase in javascript. Array is a collection of items and these items can be of same data type or not. In case of string data type, we can have lowercase as well as uppercase strings. From a developer perspective, it can be a bit tricky to convert an array to uppercase.
There are numerous ways to convert an array to uppercase. But for the sake of simplicity, we will use map()
method and toUpperCase()
to accomplish our goal. The map()
method calls a certain function for each element and return a new array. The toUpperCase()
method converts a string into an uppercase string.
In the following example, we have one global array of strings. Upon click of a button, we will convert the array to uppercase and display the result on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 2 elements in the HTML file (
button
andul
). - The
innerText
for the button element is“Get”
. - The
ul
element is empty for now and we will populate it dynamically using javascript. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <button>Get</button> <ul></ul> <script src="script.js"></script> </body> </html>
Javascript
- We have a global variable
users
and it holds an array of strings. - We have the
showUsers()
method which is responsible for populating ourul
element. - In
showUsers()
method, we are simply looping through theusers
array and creating a template string with a bunch ofli
elements. - We are displaying that list in the
ul
element. - We have selected the
button
element using thedocument.querySelector()
method and attached aclick
event listener to it. - In the event handler function, we are using
map()
method and callingtoUpperCase()
method of each element to convert each element into lowercase. - Finally, we are calling
showUsers()
method to update the list of theusers
.
let users = ['Dan', 'Gal', 'Tarry', 'Perry']; function showUsers(){ let template = users.map(user => `<li>${user}</li>`).join('\n'); document.querySelector('ul').innerHTML = template; } showUsers(); document.querySelector('button').addEventListener('click', () => { users = users.map(item => item.toUpperCase()); showUsers(); });