title: I want to print the last 'n' elements of an array
body: <p>I am writing a JavaScript function to get the last 'n' elements of the array. If array has 6 elements and if user gives 4, it has to return last 4 elements. If user gives ‘n’ which is greater than the number of elements in the array, then it should return all elements. </p>
  
  <p>The problem is if If the array has 8 elements and I give number 10. The result is : <code>undefined undefined 1 2 3 4 5 6 7 8</code></p>
  
  <p>I want to display only the numbers without "undefined".</p>
  
  <p>Thanks</p>
  
  <p>HTML code</p>
  
  <p>The array is : </p>
  
  <pre><code>1,2,3,4,5,6,7,8
  
          &lt;br&gt;
          x:
          &lt;input type="number" id="x" value="2" &gt;
          &lt;br&gt;
          &lt;button onclick="elements()"&gt; Get the elements &lt;/button&gt;
  
          &lt;p id="result"&gt;&lt;/p&gt;
  
      &lt;script src="ex10.js"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>JavaScript code </p>
  
  <pre><code> var Elements = new Array(1,2,3,4,5,6,7,8);
  
      function elements(){
      var x = document.getElementById("x").value;
  
      for(var i=Elements.length - x; i &lt;=Elements.length-1; i++)
      {
      document.getElementById("result").innerHTML += Elements[i] + " ";
      }
  
  }
  </code></pre>