A Javascript array is a variable that contains multiple values at once. The first and last elements are accessed using the index, the first value is accessed using index 0, and the last element can be accessed via the length property, which has one more value than the highest array index.
The program accesses the first and last items in the 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>
The output is as follows:
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>
The output is as follows:
First element is Geeks
Last element is science