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> |
chevron_right
filter_none
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> |
chevron_right
filter_none
Output:
First element is Geeks Last element is science
Recommended Posts:
- How to get the last item of JavaScript object ?
- JavaScript | Remove the last item from an array
- How to get the first and last date of current month using JavaScript ?
- How to Get First and Last Element of Slice in Golang?
- How to insert an item into array at specific index in JavaScript?
- How to replace an item from an array in JavaScript?
- How to get the last character of a string in JavaScript?
- How to get value of a string after last slash in JavaScript?
- How to find if two arrays contain any common item in Javascript?
- Last-child and last-of-type selector in SASS
- How to delete an item or object from the array using ng-click ?
- How to make the cursor to hand when a user hovers over a list item using CSS?
- How to remove indentation from an unordered list item using CSS?
- How to make whole area of a list item in navigation bar is clickable using CSS ?
- How to change the list item bg-color individually using ngFor in Angular 2+ ?
- How to get the first day of the year in JavaScript ?
- How to get the first key name of a JavaScript object ?
- Program to Insert new item in array on any position in PHP
- PHP program to add item at the beginning of associative array
- How to insert an item at the beginning of an array in PHP ?
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.


