Hello.
While trying to do the ‘Confirm the ending’ challenge, I tried the following code, that didn’t work, and I would like to understand why; I am not interested in the solution per se but in understanding why it does not work. When doing the console.log(function) I can see it always returns ‘False’.
function confirmEnding(str, target) {
target = [...target];
str = [...str];
let cortar = str.length - target.length;
str.splice(0,cortar);
if (str == target){
return true;
}
else {return false};
}
What I did was, first transforming the arguments in arrays; then I take the length of both arrays. Using a substraction and the splice() method I cut elements of str so that str is now composed by the last elements coinciding in length with target length. For example, If target.length is 1 and str.length is 7, then my code obtain 6 and cuts 6 elements from str[0] . So it lets only the one last elements.
Then I compare str array and target array.
I hope I was clear. Sorry, english is not my native language.
Thanks.
Yeah, about that… “you” aren’t doing that, the JavaScript interpreter is doing that. This difference is important because you do not know HOW it compares the two. The answer is: It’s looking at their memory adress. As those are different arrays, they have different adresses and thus are not equal, even if their content would happen to be identical.
While you could workaround that and compare each element…
You already figured you can cut the content of the string, so you can compare the final letters with target. How about you cut the ACTUAL STRING without turning it into an array?
String comparisons do indeed go character-by-character.
function confirmEnding(str, target) {
let ini = str.length - target.length;
let fin = str.length;
let cadena = str.slice(ini,fin);
if (cadena == target) {
return true;}
else {return false;};
return str;
}
Good job ^^
But please don’t share working code on the forum or at least use the spoiler-tag (on Desktop it’s hidden behind the kog-symbol in the editor).