Confirm the ending. Why it does not work?

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 = [];
str = [...str];
let cortar = str.length - target.length;
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.

Please provide a link to the challenge.

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.

1 Like

Thank you very much. I understand.

I did it, and it worked. Thanks.

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;

1 Like

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).

Dear Jagaya. Thank you for your help. I spoiled the code.

1 Like

I’d just like to point out that your final if/else block

if (cadena == target) {
  return true;
else {
  return false;

could be simplified to

return cadena == target;

because cadena == target evaluates to a boolean value (true or false).