Confirm the Ending only true

Hi guys,
I’m a little stuck here with this challenge.
My code seems to work but only in cases of “true”.
Can you tell me what I’m doing wrong (without altering the way I chose to solve this if it’s possible)
Thanks in advance.

This is my code:

function confirmEnding(str, target) {
  // "Never give up and good luck will find you."
  // -- Falcor
  for(var i=str.length, char = str[i];i>0; i--){
    for(var j=target.length, tarChar = target[j]; j>0; j--){
      if (char == tarChar){
        return true;
      }
       else{
         return false;
       }
    }
    
  }
//  return str;
}

confirmEnding("Bastian", "n");

Link to the challenge:
https://www.freecodecamp.org/challenges/confirm-the-ending

In your outer for loop, you start with i = str.length. In the test case confirmEnding(“Connor”, “n”), str.length = 6. String indexes start at zero and end at the string’s length - 1, so str[6] is undefined. In side the inner for loop, j = target.length and target’s length is 1. so target[1] is also undefined. Your if statement compares undefined to undefined and since they are equal, your function returns true.

I will let you in on another issue your code has. Your inner for loop will only iterate one time before returning true or false. Why? Because once a return statement is executed, the function is immediately exited and does not finish looping.

1 Like

Thanks a lot!!
I’ve managed to advance a bit but stuck again (I know why but don’t know how to get out of it :slight_smile: )
The problem now is that when the I have a whole word in the target, but this word is not the ending of the original string, it’s nor true nor false

function confirmEnding(str, target) {
  // "Never give up and good luck will find you."
  // -- Falcor
  var answer;
  for(var i=str.length-1, char = str[i];i>=0; i--){
    for(var j=target.length-1, tarChar = target[j]; j>=0; j--){
      if (char == tarChar){
         answer = 1;
       }else answer = 0;
    }
    
  }
  if (answer == 1) {
    return true;
  }
  else return false;
 // return str;
}

confirmEnding("Bastian", "n");