In this blog post you’ll learn how to get the first and last item from an array using JavaScript. We’ll see different approaches to get the first and last item from the array.
JavaScript Method Used:
pop()
shift()
slice()
at()
Get First and Last Item From Array.
Approach 1: Using pop() and shift() Method.
pop() method removes the last item from the array and stores it.
shift() method removes the first item from an array and stores it.
JavaScript
let text_array = ["hello", "welcome", "to", "maketechstuff.com"];
document.write(text_array.shift()); // hello
document.write("<br>");
document.write(text_array.pop()); // maketechstuff.com
Approach 2: Using Slice() Method.
Slice method returns the selected items from the array by defining the start and end parameters.
JavaScript
let text_array = ["hello", "welcome", "to", "maketechstuff.com"];
document.write(text_array.slice(0,1)); // hello
document.write("<br>");
document.write(text_array.slice(text_array.length-1)); // maketechstuff.com
Approach 3: Using length property as an index value to extract the array item.
JavaScript
let text_array = ["hello", "welcome", "to", "maketechstuff.com"];
document.write(text_array[0]); // hello
document.write("<br>");
document.write(text_array[text_array.length - 1]); // maketechstuff.com
Approach 4: Using at() method.
Its return the item from array based on index value given.
JavaScript
let text_array = ["hello", "welcome", "to", "maketechstuff.com"];
document.write(text_array.at(0)); // hello
document.write("<br>");
document.write(text_array.at(text_array.length-1)); // maketechstuff.com
So thats how easily you can get the first and last value from the array in JavaScript. If you have any question or suggestion feel free to write them in the comment section.
Share your thoughts.