IMG-LOGO

How to get the last object element in Javascript Array?

andy - 04 Oct, 2019 2139 Views 0 Comment

In this tutorial, you will learn how to get the last object element in Javascript Array. Before we start, you may wonder what is an array in Javascript. Array is an object to store multiple values in a single variable. The type of the value can be anything either an integer type, a string type or even an object type.

To get the last element of an array, firstly we need to identify the length of the array. We can easily get the length of an array by using the built-in attribute function called length

Please see below example of our array declaration in Javascript.

//we declare an array variable
var foods = ['burger', 'fried rice', 'pasta', 'chips', 'bread'];

To get the length of the array, we use the attribute length.

var arrayLength = foods.length;

As you know the starting index of an array is from index 0. So what we need to do is to return the total length of the array and minus it by 1. For example, if we want to get the first element of the array object, we can use the following code.

//This will return a value of burger.
var firstObject = foods[0];

So to get the last element of an array, we can use the following code.

var lastObject = foods[foods.length - 1];

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles