Why doesn't this work?

I couldn’t post a reply in this thread for some reason :expressionless:

http://forum.freecodecamp.org/t/freecodecamp-challenge-guide-confirm-the-ending/16006/44

The below solution doesn’t work for some reason. I know its a complex way to do it. I ultimately used str.split(’’).reverse(); to solve the problem but would like to understand why the below doesn’t work

function confirmEnding(str, target) {

  // "Never give up and good luck will find you."

  // -- Falcor

if(str.length<target.length){

  return false;

}

let strLength = str.length;

let targetLength = target.length;

console.log(str[strLength-1]);

console.log(target[targetLength-1]);

  for(let i=0;i<targetLength;i++){

    if(str[strLength-i] != target[targetLength-i]){

    return false;

    } 

  }

  return true;

}

confirmEnding("Bastian", "n");

this is undefined at first iteration
you don’t have anything at str[strLength] (as i at first iteration is 0)
and if the target has length of 1, that is also the only thing you check, as after that the loop stops

1 Like

Thank you so much for your reply. Such a dumb error. :expressionless:
So made it work with the below change. Thanks :slight_smile:

function confirmEnding(str, target) {

  // "Never give up and good luck will find you."

  // -- Falcor

if(str.length<target.length){

  return false;
}
let strLength = str.length;
let targetLength = target.length;
  for(let i=0;i<targetLength;i++){
    if(str[strLength-i-1] != target[targetLength-i-1]){
    return false;
    } 
  }
  return true;
}
confirmEnding("Congratulation", "on");

I admit I would have made i start at 1, and make it stop one later (at targetLength instead of at targetLength-1), but it works
congratulations!

1 Like