- Array.prototype.at()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Return the last value of an array
- Comparing methods
- Calling at() on non-array objects
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- How to Get the Last Item in an Array in JavaScript
- How to Get the Last Item in a JavaScript Array
- Method 1: Use index positioning
- Method 2: When you don’t know the array length
- Array.prototype.findLast()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Find last object in an array matching on element properties
- Using arrow function and destructuring
- Find last prime number in an array
- Using findLast() on sparse arrays
- Calling findLast() on non-array objects
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
Array.prototype.at()
The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.
Try it
Syntax
Parameters
Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if index < 0 , index + array.length is accessed.
Return value
The element in the array matching the given index. Always returns undefined if index < -array.length or index >= array.length without attempting to access the corresponding property.
Description
The at() method is equivalent to the bracket notation when index is non-negative. For example, array[0] and array.at(0) both return the first item. However, when counting elements from the end of the array, you cannot use array[-1] like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading array[«-1»] , which is just a normal string property instead of an array index.
The usual practice is to access length and calculate the index from that — for example, array[array.length — 1] . The at() method allows relative indexing, so this can be shortened to array.at(-1) .
The at() method is generic. It only expects the this value to have a length property and integer-keyed properties.
Examples
Return the last value of an array
The following example provides a function which returns the last element found in a specified array.
// Our array with items const cart = ["apple", "banana", "pear"]; // A function which returns the last item of a given array function returnLast(arr) return arr.at(-1); > // Get the last item of our array 'cart' const item1 = returnLast(cart); console.log(item1); // 'pear' // Add an item to our 'cart' array cart.push("orange"); const item2 = returnLast(cart); console.log(item2); // 'orange'
Comparing methods
This example compares different ways to select the penultimate (last but one) item of an Array . While all the methods shown below are valid, this example highlights the succinctness and readability of the at() method.
// Our array with items const colors = ["red", "green", "blue"]; // Using length property const lengthWay = colors[colors.length - 2]; console.log(lengthWay); // 'green' // Using slice() method. Note an array is returned const sliceWay = colors.slice(-2, -1); console.log(sliceWay[0]); // 'green' // Using at() method const atWay = colors.at(-2); console.log(atWay); // 'green'
Calling at() on non-array objects
The at() method reads the length property of this and calculates the index to access.
const arrayLike = length: 2, 0: "a", 1: "b", 2: "c", // ignored by at() since length is 2 >; console.log(Array.prototype.at.call(arrayLike, 0)); // "a" console.log(Array.prototype.at.call(arrayLike, 2)); // undefined
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 27, 2023 by MDN contributors.
Your blueprint for a better internet.
How to Get the Last Item in an Array in JavaScript
When you’re programming in JavaScript, you might need to get the last item in an array. In this tutorial, we’ll go over two different ways to do this.
How to Get the Last Item in a JavaScript Array
Method 1: Use index positioning
Use index positioning if you know the length of the array.
const animals = [‘cat’, ‘dog’, ‘horse’]
Here we can see that the last item in this array is horse.
To get the last item, we can access the last item based on its index:
const finalElement = animals[2] ;
JavaScrip arrays are zero-indexed. This is why we can access the horse element with animals[2]. If you aren’t sure on what zero-indexed means, we’ll go over it later on in this tutorial.
This method of getting the final item in the array works if you know the length of the array.
But what if you don’t know the length of the array? This array, animals , is very small. But you could have another array that has dozens of items in it, and you might not know its length.
Method 2: When you don’t know the array length
To get the last item in an array when you don’t know the length of that array:
const lastItem = animals[animals.length — 1] ;
The lastItem variable now holds the value of horse.
Let’s break down what’s happening in the above line. First of all, let’s just console log animals.length:
If you aren’t familiar with the length property, it returns the length of this array. This prints out 3 , because there are 3 items in the array.
Earlier we learned that JavaScript arrays are zero-indexed. This just means that in JavaScript arrays, you start counting from zero instead of from one. We can see this by looking at our animals array. cat is at index 0 , dog is at index 1 , and horse is at index 2 .
You might still be confused. We just learned that animals.length will tell us how many items are in an array. We also learned that with JavaScript arrays, we start counting from zero instead of one. But how does this help explain why we can get the last item in this array by using animals[animals.length — 1]?
Let’s imagine for a moment that JS arrays were not zero-indexed, and we started counting from 1, which is the way we normally count things in the real world.
With the animals array, we could quickly start counting and say that cat , the first item, has an index of 1, dog has an index of 2 , and horse has an index of 3 . The key insight here is that, in one-based indexing, the index of the last item is the length of the array. If the array has a length of 3, you know that the last element in the array has an index of 3 . So animals[3] would evaluate to horse .
Yet JavaScript arrays start from 0. So if we want to figure out the index of the last item in a JavaScript array, we can subtract 1 from the length of the array:
Inside of the brackets, animals.length — 1 evaluates to 2 . We now have the last item in the array.
In this article, we’ve learned two methods for how to get the last item in a JavaScript array.
If you enjoyed this post, join my coding club, where we tackle coding challenges together every Sunday and support each other as we learn new technologies.
If you have feedback or questions on this post, or find me on Twitter @madisonkanna.
Array.prototype.findLast()
The findLast() method iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.
- the first element that matches, use find() .
- the index of the last matching element in the array, use findLastIndex() .
- the index of a value, use indexOf() . (It’s similar to findIndex() , but checks each element for equality with the value instead of using a testing function.)
- whether a value exists in an array, use includes() . Again, it checks each element for equality with the value instead of using a testing function.
- if any element satisfies the provided testing function, use some() .
Try it
Syntax
findLast(callbackFn) findLast(callbackFn, thisArg)
Parameters
A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:
The current element being processed in the array.
The index of the current element being processed in the array.
The array findLast() was called upon.
A value to use as this when executing callbackFn . See iterative methods.
Return value
The value of the element in the array with the highest index value that satisfies the provided testing function; undefined if no matching element is found.
Description
The findLast() method is an iterative method. It calls a provided callbackFn function once for each element in an array in descending-index order, until callbackFn returns a truthy value. findLast() then returns that element and stops iterating through the array. If callbackFn never returns a truthy value, findLast() returns undefined .
callbackFn is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined .
findLast() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn . Therefore:
- callbackFn will not visit any elements added beyond the array’s initial length when the call to findLast() began.
- Changes to already-visited indexes do not cause callbackFn to be invoked on them again.
- If an existing, yet-unvisited element of the array is changed by callbackFn , its value passed to the callbackFn will be the value at the time that element gets visited. Deleted elements are visited as if they were undefined .
Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The findLast() method is generic. It only expects the this value to have a length property and integer-keyed properties.
Examples
Find last object in an array matching on element properties
This example shows how you might create a test based on the properties of array elements.
const inventory = [ name: "apples", quantity: 2 >, name: "bananas", quantity: 0 >, name: "fish", quantity: 1 >, name: "cherries", quantity: 5 >, ]; // return true inventory stock is low function isNotEnough(item) return item.quantity 2; > console.log(inventory.findLast(isNotEnough)); //
Using arrow function and destructuring
The previous example might be written using an arrow function and object destructuring:
const inventory = [ name: "apples", quantity: 2 >, name: "bananas", quantity: 0 >, name: "fish", quantity: 1 >, name: "cherries", quantity: 5 >, ]; const result = inventory.findLast(( quantity >) => quantity 2); console.log(result); //
Find last prime number in an array
The following example finds the last element in the array that is a prime number (or returns undefined if there is no prime number):
function isPrime(element) if (element % 2 === 0 || element 2) return false; > for (let factor = 3; factor Math.sqrt(element); factor += 2) if (element % factor === 0) return false; > > return true; > console.log([4, 6, 8, 12].findLast(isPrime)); // undefined, not found console.log([4, 5, 7, 8, 9, 11, 12].findLast(isPrime)); // 11
Using findLast() on sparse arrays
Empty slots in sparse arrays are visited, and are treated the same as undefined .
// Declare array with no elements at indexes 2, 3, and 4 const array = [0, 1, , , , 5, 6]; // Shows all indexes, not just those with assigned values array.findLast((value, index) => console.log(`Visited index $index> with value $value>`); >); // Visited index 6 with value 6 // Visited index 5 with value 5 // Visited index 4 with value undefined // Visited index 3 with value undefined // Visited index 2 with value undefined // Visited index 1 with value 1 // Visited index 0 with value 0 // Shows all indexes, including deleted array.findLast((value, index) => // Delete element 5 on first iteration if (index === 6) console.log(`Deleting array[5] with value $array[5]>`); delete array[5]; > // Element 5 is still visited even though deleted console.log(`Visited index $index> with value $value>`); >); // Deleting array[5] with value 5 // Visited index 6 with value 6 // Visited index 5 with value undefined // Visited index 4 with value undefined // Visited index 3 with value undefined // Visited index 2 with value undefined // Visited index 1 with value 1 // Visited index 0 with value 0
Calling findLast() on non-array objects
The findLast() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .
const arrayLike = length: 3, 0: 2, 1: 7.3, 2: 4, 3: 3, // ignored by findLast() since length is 3 >; console.log( Array.prototype.findLast.call(arrayLike, (x) => Number.isInteger(x)), ); // 4
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- Polyfill of Array.prototype.findLast in core-js
- Indexed collections
- Array
- Array.prototype.find()
- Array.prototype.findIndex()
- Array.prototype.findLastIndex()
- Array.prototype.includes()
- Array.prototype.filter()
- Array.prototype.every()
- Array.prototype.some()
- TypedArray.prototype.findLast()
Found a content problem with this page?
This page was last modified on Jun 27, 2023 by MDN contributors.
Your blueprint for a better internet.