Get the first and last item in an array using JavaScript


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

First element is 3 
Last element is 5

Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

First element is Geeks
Last element is science 


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

About immukul

Executive Software Developer at Cavisson Systems