4

Get last element of array in JavsScript

 2 years ago
source link: https://dev.to/vickyktk/get-last-element-of-array-in-javsscript-2n0h
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Get last element of array in JavsScript

Whatever the programming language you code in ,I am sure you will be playing with arrays every day. So today we will be looking at options we can get the last element of an array in Javascript.

METHOD 1:INDEXING

When You know the lenght of the array:

Say we have the following array

var myArr = ['Apple', 'Orange', 3, 4, 'Football', 'Cricket'];
So as we know that arrays are zero-indexed in programming, which means that the first element is placed at zero position(Dont tell this to your non-programmer friend). So we just need to count the number of element in the array, which is six(6) in our case so

console.log(myArr[5])

Enter fullscreen mode

Exit fullscreen mode

will print the last element('cricket') for us. Easy Right. Now let's buckle up for the hard part.

METHOD 2:USING length FUNCTION

If the array is uncountable for human or coming as function argument than we can use javascript length function to get the last element. This will be like

console.log(myArr[myArr.length - 1])

Enter fullscreen mode

Exit fullscreen mode

myArr.length will give us the array lenght and 1 less from lenght will give the index of last element of the array.

METHOD 3: USING .pop() FUNCTION

We can get the last element of array with .pop() function like this

let last =myArr.pop()
console.log(last)

Enter fullscreen mode

Exit fullscreen mode

But there is a problem with this function as our array will be reduced to five items now as last element is popup out by the function. But if you were to use the array in your code again, you can have a copy of the array.

let myArray2 = myArr
let last =myArr.pop()

Enter fullscreen mode

Exit fullscreen mode

So now myArray2 have all the elements of original array and you can perform any task you want.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK