Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Why do I get the error message "undefined"?

Joesson

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

JavaScript:
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:

JavaScript:
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!
 
indexOf() give the first occurrence of a value in a string. Try this just to see the difference.
<script>
function lastElement ([Good, Bad, Ugly])
{
let text = "Good, Bad, Ugly";
let index = text.indexOf('Ugly');
return index;

}
let Bill = lastElement('Loafy', 'Boafy', 'Goafy');
alert(Bill);
</script>You are not going to get Goafy . If that is what you want to get Use arguments[2]. Arguments are in an array so theyb start with zero.
 
Last edited:

New Threads

Buy us a coffee!

Back
Top Bottom