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
It works because it starts at the end
Why bother with looping?