I am doing some assignements in JS, and I have written afunction to compare the ending of a string (str) and return true or false if it matches the "target" string (this could be done a lot easier, but this piece of mayhem is how I chose to go about it):
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 actually works, but looking at it, I cant understand why…
If I run
confirmEnding("Testing123", "tin5123");
It should return true in my mind, but the for loop does not change the value of variable "valid" back to true after the 4th iteration of the for loop? (shouldnt the for loop iterate 5, 6 and 7 also and go back to "true" for "valid"?)
The answer I get from OpenAI is that the function is checking that the "target" matches the end of "str". How? I cant see anywhere that I have made any specific instruction to do that…
How does the function decide which value of the variable "valid" to return? Does it iterate through all and only return "if: valid = true" if ALL i are true? Why?
Thanks
3
Answers
It works because it starts from the end
Why even bother with the loop?
This is because your loop overrides the value of valid.
For example we have loop 1 – 10 and you have boolean isThereFour and You will check it for all the numbers it will return false not true. It is going to be true but only for one time. You should break the loop to see the actual situation.
Add some logging to the code (this and/or using a debugger to step through the code, is the most important thing you can do when you trying to understand how code gets the result it gives):
It compares the last character in each string, and then does nothing with the result.
Then it compares the last two characters in each string, and then does nothing with the result.
Then, several loops later, it compares the second string with the substring of the first string with finishes at the end and is the same length, and returns that result.
No. You’re comparing substrings from 𝒩 to the end of the string. You’re not comparing single characters.
It returns the last value you give to
valid
, because that is the value it has when youreturn
it.