0

I'm trying to create a function that checks if a given string is a palindrome. I had some difficulty getting it to work with capital letters, but I think(?) that's fixed now. The issue is that when I pass my string into the checkString() function, it returns undefined and I don't know why.

const palindromes = function(string) {
  const originalString = string;
  const reverseString = string.split("").reverse().join("");
  const check = reverseString.slice(-1);

  if (check === check.toUpperCase()) {
    const newString = reverseString.slice(0, 1).toUpperCase() + originalString.slice(1);
    checkString(originalString, newString);
  } else {
    checkString(originalString, reverseString);
  };
};


const checkString = function(originalString, newString) {
  if (originalString === newString) {
    return true;
  };
  return false;
};

console.log(palindromes("Racecar"));

Any hints would be appreciated.

VLAZ
  • 26,331
  • 9
  • 49
  • 67

2 Answers2

1

You need to return the value returned by checkString() function.

const palindromes = function(string) {
  const originalString = string;
  const reverseString = string.split("").reverse().join("");
  const check = reverseString.slice(-1);

  if (check === check.toUpperCase()) {
    const newString = reverseString.slice(0, 1).toUpperCase() + originalString.slice(1);
    return checkString(originalString, newString);
  } else {
    return checkString(originalString, reverseString);
  };
};


const checkString = function(originalString, newString) {
  if (originalString === newString) {
    return true;
  };
  return false;
};

console.log(palindromes("Racecar"))
TechySharnav
  • 4,869
  • 2
  • 11
  • 29
1

You can make your code even better:

const palindromes = function(string) {
  const originalString = string.toUpperCase(); // make string to uppercase
  const reverseString = originalString.split("").reverse().join(""); // reverse string
  return originalString === reverseString; // inline compare and RETURN the value!
};


console.log(palindromes("Racecar"));
console.log(palindromes("stackoverflow"));
stacj
  • 1,103
  • 1
  • 7
  • 20