Skip to content
Related Articles

Related Articles

Get the first and last item in an array using JavaScript

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 24 Nov, 2021

In this article, we will learn to get the first & last element in an array in Javascript, along with understanding their implementation through the examples.

Javascript array is a variable that holds multiple values at a time. The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index. The array length property in JavaScript is used to set or return the number of elements in an array.

Example 1: This example illustrates to access the first and last number in the array.

Javascript




<script>
  // Array 
  let s=[3, 2, 3, 4, 5]; 
  function Gfg() {
    
    // Storing the first item in a variable 
    let f=s[0];
      
    // Storing the last item 
    let l=s[s.length-1]; 
      
   // Printing output to screen
   document.write("First element is "+ f); 
   document.write("<br> Last element is "+ l); 
  
  Gfg(); // Calling the function
</script>


Output:

First element is 3 
Last element is 5

Example 2: This example illustrates to access the first and last word in the array.

Javascript




<script>
  // Simple array
  let s= ["Geeks", "for", "geeks", "computer", "science"]; 
  function Gfg() { 
    
  // First item of the array
   let f=s[0]; 
     
  // Last item of the array
   let l=s[s.length-1]; 
     
  // Printing the output to screen
   document.write("First element is "+ f); 
   document.write("<br> Last element is "+ l); 
   
  Gfg(); // Calling the function 
</script>


Output:

First element is Geeks
Last element is science 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!