Beginner question about function with an array parameter/argument

Hello, newbie here. Why does this code tell me that lastElement is undefined?

function lastElement ([Good, Bad, Ugly])
{
    let index = lastElement.indexOf('Ugly');
    return index;
 
}

lastElement('Loafy', 'Boafy', 'Goafy');

I also tried a different version of it, which returns as undefined as well:

function lastElement ([val1, val2, val3])
{
    let index = lastElement[lastElement.length -1];
    return index;
 
}

lastElement('Loafy', 'Boafy', 'Goafy');

I thought that the contents of ‘lastElement’ would be defined by the user when passing the argument, and so by then it would be defined? What am I missing?

I am trying to return the last element of the array, when the function is called.

Thanks!

well, because lastElement is the name of the function, not the parameter you’re passing to it.

Are you trying to pass an array, or are you trying to pass 3 things? (You can’t “indexOf” 3 individual things, you would have to put them together in a collection first.)

function lastElement(imanarray) {
   let index = imanarray.indexOf("Ugly")
  return index
}

...
lastElement(["Loafy","Boafy","Ugly"]) //Returns 2.
lastElement(["Loafy","Boafy","Goafy"]) //Returns -1.

Or, if it’s the last item of an array that you want to return, you can do that in this manner:

function lastElement(arr) {
   return arr[arr.length - 1];
}

lastElement(["Loafy","Boafy","Ugly"]) //Returns "Ugly"
lastElement(["Loafy","Boafy","Goafy"]) //Returns "Goafy"

Thank you m_hutley and Paul_Wilkins for your clarifications! That clears things up for me. For some reason I thought you had to include the array enclosure [ ] in the initial parameter inside of the ().

About Paul’s response: would I also be able to achieve this using .findLastIndex?

Yes, you can certainly use .findLastIndex but some web browsers will break.

function lastElement(arr) {
   return arr[arr.findLastIndex];
}

Here’s a very handy website that tells you which browsers can and can’t use certain features.

An alternative that would work in all browsers (yes, even ye olde IE) would be array.pop() instead; note that this does mean that the array loses the last element, if your code continues and expects the full array, but… basically you’re recreating this function anyway.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.