Home > Mobile >  isPalindrome - how comparison is being executed in `else if (str.length===2) return str[0]===str[1]
isPalindrome - how comparison is being executed in `else if (str.length===2) return str[0]===str[1]

Time:10-01

I understand the 3rd Conditional but not 2nd one

On the 2nd Conditional - if the length of "str" is 2 (meaning it has 2 characters) then return "str[0] === str[1]" but what if those last two characters are different "c" "g" maybe?

how comparison is being executed in return str[0] === str[1] ? does the comparison have to be inside if() statement because if() statement returns true ?

However, this line return str[0] === str[1] being outside the scope of if() statement return true or false

function isPalindrome(str) {
  // 1st Conditional
  if (str.length === 1) return true 

  // 2nd Conditional
  else if (str.length===2) return str[0]===str[1] 
  
  // 3rd Conditional
  else if (str[0] === str.slice(-1)) {
    return isPalindrome(str.slice(1,-1))
  }

  return false
}

CodePudding user response:

return "str[0] === str[1]", but what if those last two characters are different "c" "g" maybe?

This statement will return a boolean value. That boolean value is determined by str[0] === str[1]. This is a comparison that is either false or true. In the example "cg", that comparison will evaluate to false, and so the return statement will make the function return with the value false.

how comparison is being executed in return str[0] === str[1]?

It is executed like in any other context. The expression is str[0] === str[1], and the result of that evaluation is returned by the return statement.

does the comparison have to be inside if() statement because if() statement returns true ?

The return should only be executed when the preceding if statement is true, i.e. that return should only be executed when the length of the string is true.

However, this line return str[0] === str[1] being outside the scope of if() statement return true or false

That statement is not outside the scope of the if statement. It is a statement that is only executed when the if condition is true.

If it helps, we could rewrite that if (str.length===2) return str[0]===str[1] as follows:

if (str.length===2) {
    let isPalindromeOfTwo = str[0]===str[1];
    return isPalindromeOfTwo;
}

Or even (but this is an antipattern):

if (str.length===2) {
    if (str[0]===str[1]) {
        return true; // It is a palindrome of 2
    } else {
        return false; // Not a palindrome
    }
}

Just realise that a comparison represents a value: a boolean value. This value can be used in any context that requires a value. You can for instance do any of these:

console.log(str[0]===str[1]); // output will be "false" or "true"
let x = str[0]===str[1]; // x will be a boolean value: false or true
let y = Number(str[0]===str[1]); // y will be a number, 0 or 1
  • Related