Get the last element of the array (without changing the array). Use function I have such a code to get, is it correct? And how to put it in the function?

let index = [1, 2, 4, 5, 7, 8]; for (let i = 0; i<index.length; i++); console.log(index.pop()) 

    2 answers 2

    The returnLastItem function will return the last element of the array passed to it:

     let myArray = [1, 2, 4, 5, 7, 8]; let myArray2 = [1, 2, 4, 5, 7, 15]; function returnLastItem(arr) { return arr[arr.length - 1]; } console.log(returnLastItem(myArray)); console.log(returnLastItem(myArray2)); 

    eight

    15

    If the function always has the same array, it will look like this:

     function returnLastItem() { let myArray = [1, 2, 4, 5, 7, 8]; return myArray[myArray.length - 1]; } console.log(returnLastItem()); 

    The second method is not a very good solution, because it deprives you of flexibility when using the function - in the first example you can get the last element of any array, in the second only the one defined inside.

    • Thank you very much. - Matc

    It is not very clear what you are trying to do. You do a search, but at the same time use the pop method, which deletes the last element of the array and returns its value, while the search is just a tick. The question can be easier, just find out the number of elements in the array (the length method) and use this value as a key.

     let index = [1, 2, 4, 5, 7, 8]; console.log(index[index.length - 1]); 

    • And how to put it in the function? - Matc
    • @Matc in the next answer showed how - Peresada