We are going to cover very basic approach in this tutorial to find middle element in an array. The approach is beginner friendly and easy to understand. Please have a look over example code and steps given below.
We have 2 elements in the HTML file (button and h1)
We have done some basic styling using CSS.
We have created users variable which holds array of strings as value.
We have added click() event listener to the button element, so that we can get middle element of the array and display it on the screen.
As you already know, indexes in array are 0 based. To find the middle element, first we need to get length of the array using length property and subtract 1 from it. Then, we need to divide it by 2 to get the middle element. In our case, length of array is an odd number. In case the length is even number, I recommend you to wrap the output with Math.floor() function.
We are storing the result of above calculation in output variable.
Now that we have got our output which is the index of middle element in the array, we can display its value inside h1 element.