➤ How to Code a Game
➤ Array Programs in Java
➤ Java Inline Thread Creation
➤ Java Custom Exception
➤ Hibernate vs JDBC
➤ Object Relational Mapping
➤ Check Oracle DB Size
➤ Check Oracle DB Version
➤ Generation of Computers
➤ XML Pros & Cons
➤ Git Analytics & Its Uses
➤ Top Skills for Cloud Professional
➤ How to Hire Best Candidates
➤ Scrum Master Roles & Work
➤ CyberSecurity in Python
➤ Protect from Cyber-Attack
➤ Solve App Development Challenges
➤ Top Chrome Extensions for Twitch Users
➤ Mistakes That Can Ruin Your Test Metric Program
A container object called an array carries a predetermined number of values of a single kind. Once constructed, the length of an array would not change. Now that we understand the basics of an array let’s discover the final element in an array.
If you know the array’s size, you should use index placement. Let’s make an array first:-
const animals = ["cat", "dog", "horse"];
We can use the last item’s index to reach it and acquire it:-
const lastElement = animals;
If you know the array’s length, you can use this technique to find the last item in the array. What happens if you must be aware of the array’s size? This collection of animals is relatively modest. However, you might need to be mindful of the length of another array that contains dozens of objects.
When you don’t know an array’s length, here’s how to acquire its last item: array[array.length – 1].
const animals = ["cat", "dog", "horse"]; const lastElement = animals[animals.length - 1]; console.log("Last element: " + lastElement);
Last element: horse
The length property returns the length of this array, in case you are unfamiliar. As there are 3 elements in the array, 3 is printed.
const planets = ["Mercury", "Venus", "Earth", "Moon"]; const lastElement = planets.pop(); console.log("Last element: " + lastElement); console.log("New array: " + planets);
Last element: Moon
New array: Mercury, Venus, Earth
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!