How to print N no. of elements of array each time on click

I have an array of 20 elements. I want to display first five elements on click of a button, then next five elements on another click, and so on. I would be grateful if you could help me with the code.


<button onclick="nextElems();"> Try </button>

<div id="yes"> </div>

 var words = ["day", "white", "go", "low", "wise", "up", "sit", "now", 
    "good", "grapes", "banana",
    "mango", "orange", "pears", "melon", "guava", "sunflower", "marigold", 
    "jasmine", "sunflower"];

    var x = "";

    var count = 0;

    function nextElems() {

        if (count < words.length) {

            var newArray = words.slice(0, 5);

            x += '<div>' + newArray + '</div>';

            document.getElementById('yes').innerHTML = x;

            count = newArray;

        } else {

            count = 0;

            var secondArray = words.slice(5, 10);

            x += '<div>' + secondArray + '</div>';

            document.getElementById('yes').innerHTML = x;


        x = "";

You did not explain what you want to display once the last group of 5 words in the array have been displayed, but let’s assume you want to display the phrase “No more words to display”. Also, I assume you only want to show 5 words at a time and not show the older words above or below the current 5 words being shown.

Here is some pseduo-code you could use for your nextElems function:

  1. Start by assuming you are at the end of the list of words, so assign the string “No more words to show” to a variable (i.e. wordsToShow)

  2. Create a new array containing 5 elements of the words array beginning at the index value of the count variable (I would rename this to wordsIndex). Think about how you could use slice here with the wordsIndex variable to accomplish this.

  3. Check if the current value of wordsIndex is less than words.length. If it is, then assign the value of the wordsArray to wordsToShow.

  4. Update the innerHTML of the div with id=“yes” to the value of wordsToShow

  5. Increment your wordsIndex by 5 to skip to the next set of words.

This is not the only way to accomplish this, but the code is fairly simple to create from the algorithm I have outlined. See if you can write the code now.