Get last element of array in JavsScript
vickyktk

vickyktk @vickyktk

About: Junior Software Engineer !!! working on WordPress/Woocommerce Plugins development

Joined:
Dec 15, 2019

Get last element of array in JavsScript

Publish Date: Jan 18 '22
16 18

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.

Comments 18 total

  • Giorgi Kharshiladze
    Giorgi KharshiladzeJan 18, 2022

    I think you are missing one of the methods that was added not too long ago.
    Array.prototype.at(). To get the last element in an array you can do myArr.at(-1).
    developer.mozilla.org/en-US/docs/W...

    • Daniel Gropp
      Daniel GroppJan 18, 2022

      While it’s a cool new method, keep in mind that currently it’s not supported in Safari based devices.

      • Alex Lohr
        Alex LohrJan 18, 2022

        You can easily polyfill it:

        if (![].at) {
          Array.prototype.at = function(pos) { return this.slice(pos, pos + 1)[0] }
        }
        
        Enter fullscreen mode Exit fullscreen mode
      • Wojciech
        WojciechJan 19, 2022

        In Safari Technology Preview you can activate it via Develop > Experimental Features

    • vickyktk
      vickyktkJan 31, 2022

      Oh Yes !!! Thank You. This pretty usefull and easy

  • Jon Randy 🎖️
    Jon Randy 🎖️Jan 19, 2022

    A somewhat unusual way:

    const str = 'Hello'
    const {length, [length-1]: last} = str
    
    console.log(last) // 'o'
    
    Enter fullscreen mode Exit fullscreen mode
    • Wojciech
      WojciechJan 19, 2022

      Using console.log in prod is discouraged

      • Jon Randy 🎖️
        Jon Randy 🎖️Jan 19, 2022

        Naked flames in firework factories are discouraged too

        • Wojciech
          WojciechJan 19, 2022

          Laugh all you want, but console.log can be abused by some threat actors very easily. I mean, output of console.log is not escaped ( or otherwise secured ) in any way

          • Jon Randy 🎖️
            Jon Randy 🎖️Jan 19, 2022

            I'm not laughing, but your comment was entirely irrelevant. The console.log I used was simply used to display the result of some sample code - in a similar way to the way the original poster used it. No-one is suggesting in any way that it should be used in production code.

            • Wojciech
              WojciechJan 19, 2022

              OK. So imagine this:

              How are web-enabled systems attacked? Of course there are many ways, but first and the most used one method of probing is through reverse engineering output of console.log.

              • GrahamTheDev
                GrahamTheDevJan 19, 2022

                The console.log is for demonstration purposes, you can just do:

                let myNewVar = last

                and then return it or use it or whatever, the only bit that is of significance is:

                const {length, [length-1]: last} = str

                Which I am still processing as Jon always blows my mind with some weird syntax I haven't seen before (or more precisely have seen but don't use so have to then go and do a load of unpacking of his solution 🤣)!

    • jzombie
      jzombieJan 19, 2022

      This is awesome

  • Peter Vivo
    Peter VivoJan 19, 2022
      const list = ['Apple', 'Orange', 3, 4, 'Football', 'Cricket'];
      list.slice(-1)?.[0]; // 'Cricket'
      'Cricket'.slice(-1)?.[0]; // 't'
      [].slice(-1)?.[0]; // undefined
    
    Enter fullscreen mode Exit fullscreen mode
  • meirlamdan
    meirlamdanJan 19, 2022

    what you wrote at the end of the post, is not true.
    It will not help to copy the array, because it only creates a reference to that array itself
    Instead it is possible as follows

    let myArray2 = [...myArr]
    let last = myArr.pop()
    
    Enter fullscreen mode Exit fullscreen mode
Add comment