• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Return the last element in an array

Return the last element in an array

Return the last element in an array

Check if arr is truthy and has a length property. Use Array.prototype.length - 1 to compute the index of the last element of the given array and return it, otherwise return undefined.

const last = arr => (arr && arr.length ? arr[arr.length - 1] : undefined);

// Examples
last([1, 2, 3]); // 3
last([]); // undefined
last(null); // undefined
last(undefined); // undefined

Source

https://www.30secondsofcode.org/js/s/last

Miscellaneous

Related Snippets:

  • How To Format Numbers as Currency Strings in JavaScript
  • Find a Specific Element from an Array
  • Check if array has duplicates
  • Insert an HTML string after the end of the specified element

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers