Beginner question: Why does this for loop return false?
P粉022723606
P粉022723606 2023-09-08 17:31:55
0
1
454

I'm doing some homework in JS, and I wrote a function that compares the end of a string (str) and returns true or false if it matches the "target" string (this could be done easier, but I chose this chaotic way):

function confirmEnding(str, target) {
  let valid = true;
  
console.log(str.length);
  console.log(target.length);

  for(let i = 0; i < target.length; i++){
    if (str.substring(str.length - (i+1)) == target.substring(target.length - (i+1))){
      valid = true;
    }
    else{
      valid = false;
    }
  }
  
  console.log(valid);
  return valid;

}

So, this function does work, but looking at it, I don't understand why...

If I run

confirmEnding("Testing123", "tin5123");

It seems to me that it should return true, but the for loop does not change the value of the variable "valid" back to true after the fourth iteration of the for loop? (Shouldn't the for loop also iterate over 5, 6 and 7 and return "true" to get "valid"?)

The answer I got from OpenAI is that the function is checking if "target" matches the end of "str". how? I can't see anywhere that I've been given any specific instructions to do this...

How does a function decide which value of a return variable is "valid"? Does it iterate through everything and only return "if: valid = true" if ALL i is true? Why?

Thanks

P粉022723606
P粉022723606

reply all(1)
P粉575055974

It works because it starts at the end

function confirmEnding(str, target) {
  let valid = true;

  for(let i = 0; i < target.length; i++){
    console.log(str.substring(str.length - (i+1)), target.substring(target.length - (i+1)))
    if (str.substring(str.length - (i+1)) == target.substring(target.length - (i+1))){
      valid = true;
    }
    else{
      valid = false;
    }
  }
  
  return valid;

} 

console.log(confirmEnding("Testing123", "tin5123"));

Why bother with looping?

function confirmEnding(str, target) {
  return str.endsWith(target)
} 

console.log(confirmEnding("Testing123", "tin5123"));
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template