Array and Function; What am I doing wrong?


#1


I am doing a problem for some pre-work before a class I have. When I run the code on the console on codecademy, it works just fine, but when I run it on the site for my class, it returns errors. Can someone see what I'm doing wrong?

This is the error given to me:

Oops! Errors. Try again.
Function returned
two
instead of
one
when passed
["five","four","whatever, man","three","two","one"]


/*Create a function called theLastOne
that returns the last element of an array
that is passed in. Hint: This should work 
for an array of any size.*/

function theLastOne(parameter){
return parameter[4];
}

var array = [11,22,33,44,55];
var lastArray = theLastOne(array);

console.log(lastArray);


#2

In a function, the more things we can do dynamically, the more re-usable it will be.

return parameter[parameter.length - 1];

You might not have worked with many built-in functions, but JavaScript has a couple that are pretty cool, once we learn how to use them, and when. Only explore this when you've made enough progress in the track to feel comfortable with it.

function theLastOne(array) {
    return array.slice().pop();
}

It's important that we don't pop() on the array itself. As a reference object it is not in function scope, but parent scope, and will be affected by the change. So we make a temporary copy using .slice() and pop() it.

What pop() does is remove the last element of an array and return it. We don't need to assign it to a variable since we are returning it from our function. It will be the return value to the caller.

var myArray = ["five","four","whatever, man","three","two","one"];
console.log(theLastOne(myArray));
// one

#3

Thank-you so much. I have been working on this problem for a good 3-4 hours. I will try and retain this information for the future.