0
\$\begingroup\$

I hope you will tell me tips to ask good questions regarding checking my code. Here it's the code and thanks in advance!

const checkPalindrome = str => {
    str = str.toLowerCase()
    let reverse = str.split('').reverse().join('');
    return reverse === str ? true : false;    
}
console.log(checkPalindrome('Madam'));
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

There isn't much to review here; you did a good job! You've provided the canonical solution to this problem. However, here is slightly revised version of your code with some semantic modifications:

const checkPalindrome = (str) => str.toLowerCase() === str.toLowerCase().split("").reverse().join("");

console.log(checkPalindrome('Madam'));

Some notes:

  1. In JavaScript, you should use double quotes instead of single quotes whenever possible.

  2. The ternary expression ... ? true : false is redundant; the statement preceding the ternary operator will automatically evaluate to one of these values in this order.

  3. Since this function is so small, you don't really need to define the reverse variable; it is very obvious what is happening, especially as the .reverse() method is being called.

  4. Similarly, you can simply chain the toLowerCase() method to each reference of str, instead of redefining that variable.

  5. There should be a space between the definition of checkPalindrome and the console log.

Good job!

\$\endgroup\$
2
  • \$\begingroup\$ Thanks for your review, it's really informative. I appreciate that. \$\endgroup\$ May 29, 2023 at 5:25
  • \$\begingroup\$ The first note is opinionated and I have not seen a compelling argument one way or the other; they are interchangeable. \$\endgroup\$
    – morbusg
    May 29, 2023 at 11:07
1
\$\begingroup\$

The following are really minor – almost pedantic – points.

For consistency, naming functions asking for a boolean answer on their arguments are prefixed with a is, so isPalindrome would be a more idiomatic name.

You are needlessly creating an array out of the string just to reverse it. While the cost of doing so is negligible, you could do the comparison without one by iterating over half the length of the string and comparing the index position with its negative position:

function isPalindrome(str) {
  for (let i = 0; i < Math.floor(str.length / 2); i++) {
    if (str[i] !== str[str.length - 1 - i])
      return false
  }
  return true
}
\$\endgroup\$
1
  • \$\begingroup\$ Thanks for your review. \$\endgroup\$ Jun 1, 2023 at 10:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.