Skip to content
Related Articles

Related Articles

Get the first and last item in an array using JavaScript
  • Last Updated : 23 Apr, 2019
GeeksforGeeks - Summer Carnival Banner


Javascript array is a variable which 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.
Program to access first and last item in array:
Example #1:




<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:




<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 

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :