Search code examples
javascriptalgorithmecmascript-6palindrome

JS palindrome check with "every" helper method breakdown


I'm trying to understand why my input is falsy

> palindrome('abaasa')
false

Given this palindrome checker function

function palindrome(str) {
  return str.split('').every((char, i) => {
    return char === str[str.length - i - 1];
  });
}

from what I understand the, every helper does a boolean check for every value taken in from the array.

When broken down it would look like this to me.

(0 => a) === (5 => a) // truthy <--- START
(1 => b) === (4 => s) // falsy
(2 => a) === (3 => a) // truthy

I know there is more comparison than necessary, and I'm aware this needs optimization.

Continuing on the iteration, this is where the pointers intersect.

(3 => a) === (2 => a) // truthy
(4 => b) === (1 => s) // falsy
(5 => a) === (0 => a) // truthy <--- STOP 

Question

Is the every method smart enough to return false when it finds a falsy comparison?

If not how was the falsy return determined given my function?


Solution

  • You can check if it's smart enough by introducing a console.log statement inside your every function. This will allow you to actually see where it stops.

    function palindrome(str) {
      return str.split('').every((char, i) => {
        console.log(i);
        return char === str[str.length - i - 1];
      });
    }
    
    let str = 'abaasa';
    console.log(palindrome(str)); // prints: 0 1 false

    Is the every method smart enough to return false when it finds a falsy comparison?

    As you can see, it is smart enough to stop after a falsy. It only went through the indeces 0 and 1 when it could have reached 5 in total.