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

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

← PreviousNext →