-2

New to JavaScript and can't figure out what I'm doing wrong. I'm attempting to get the function to either return the last element of the array if there is such an argument (I got this part to work). And if there is no argument to return null. However, when I try to get it to return an empty array, it only returns as undefined and not null. If you could explain to me what I'm doing wrong without just showing me the answer I would be appreciative.

This is the code I have written:

function lastElement(array) {
  if (array !== "") {
    return array[array.length - 1];
  } else {
    return null;
  }
}
2
  • 2
    The only way to return null with your given logic is to pass an empty string as argument console.log(lastElement(''));. Every other value of array will enter the first block of the if. Commented Dec 1, 2022 at 11:06
  • 1
    Check for (array.length > 0), You are comparing array (type object) with "" (type string). Commented Dec 1, 2022 at 11:06

1 Answer 1

0

try with this:

function lastElement(array){
 if(array.length !== 0){
    return array[array.length - 1];
 }else{
    return null;
 }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Whilst this code snippet is welcome, and may provide some help, it would be greatly improved if it included an explanation of how and why this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now! Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.