Quick Tip: How to get the first and last element in an Array using JavaScript

← PrevNext →

You can use the find() and findLast() methods in JavaScript to get the first and last element in an array.

Here's an example.

<script>
  const arr = [6, 18, 21, 81, 13];
  
  document.write('the first value is ' + arr.find(item => item));       // Output 6.	
  document.write('the last value is ' + arr.findLast(item => item));	// Output 13.
</script>
Try it

Related tutorial... How to get the First and Last day of a given Month using JavaScript?

You can also add some conditions like, get the first and last values (or elements) that is greater than 5.

<script>
  const arr = [3, 7, 51, 3, 17, 6];
  
  document.write('the first value is ' + arr.find(item => item > 5));	    // Output 7.
  document.write('the last value is ' + arr.findLast(item => item > 5));    // Output 6.
</script>
Try it

Also read... How to use .map() function to extract only numbers from an array of values?

← PreviousNext →

Happy coding. 🙂