-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
    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`. – pilchard Dec 01 '22 at 11:06
  • 1
    Check for (array.length > 0), You are comparing array (type object) with "" (type string). – RKataria Dec 01 '22 at 11:06

1 Answers1

0

try with this:

function lastElement(array){
 if(array.length !== 0){
    return array[array.length - 1];
 }else{
    return null;
 }
}
  • 1
    Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) 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. – PeterS Dec 01 '22 at 16:17