Confirm the Ending, I'm not sure why this isn't working

I’ve tried this approach using a for loop to act as a filter to reject any false comparisons to the indexes in the string/ target. I saw the correct answers using basic data structure methods and felt like I way overcomplicated it, but I’d still like to see what part went wrong in my attempt:

function confirmEnding(str, target) {
  let strLen = str.length-1;
  let tarLen = target.length-1;
  let result;
  //below is the first index of the tar were looking for in the string
  let first = strLen-tarLen;
    // loop through the indexes from the first of target til last of the string  
  for(let i=0; i>tarLen;i++){
    if (str[(first+i)] != target[i]){
     else {
    return result;
  }return result;

confirmEnding("Bastian", "n");
len open sesame= 11, len same= 4;
so, for ^^, we'd need str index [strlen-tarLen] through index [srtlen];
                                checks this index = tar index0, then
                                then this index +1= tarindex1,
                                then this index+2 = tarindex2


I found a link that did a variation of what I thought I was doing: the way I thought I did but it was locked and I’m still confused on how my code didn’t grasp that.

Thank you for your time and patience, Algorithms have knocked my momentum with learning JS off kilter and now I am worried that I’m giving up too easily, which I certainly don’t want.

There are a few things I would recommend here. First, if you’re doing stuff where you’re playing with an idea, and you need to test it out? Pull it into a separate “sandbox” elsewhere. I use replit, and here’s your code, working:

Now, that’s first. But second, there are a couple of issues. First, you are setting strLen to str.length-1 and tarLen to target.length-1. So for your given string, strLen===6 and tarLen===0.

And then you loop using i, from 0 to tarLen times. So zero times. I found that by adding a console.log(strLen, tarLen, first) before the loop. Found that, and fixed them. In this case, you want those Len variables to be the actual length.

Then, in your for loop, you’re saying "let i equal zero, and loop as long as i is greater than tarLen". Given that it starts out less than tarLen, the loop is already not going to run. You want that loop to run as long as i is less than tarLen.

Fixed those two (the *Len variables and the greater/less thing), and it looks like its working. Check the replit above to see.

1 Like

Thank you for the tips!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.