JavaScript Algorithms and Data Structures Projects - Palindrome Checker

Tell us what’s happening:

My code is passing all tests except for when “almostomla” is passed to the palindrome function. I know it isnt very efficient at the moment.

I have tried to compare both if the array index matches and doesnt match e.g strArray[j] === reverseArray[j] and strArray[j] != reverseArray[j].

Any tips would be appreciated.

Your code so far

function palindrome(str) {
  //remove any special chars and spaces with RegEx
  let cleanStr = str.replace(/[^a-z0-9]/gi, "")
  //covert string to lower case
  let lowerCaseStr = cleanStr.toLowerCase();
  //use spread to put string into array
  let strArray = [...lowerCaseStr];
  //define new array for reversing sting
  let reverseArray = [];
  //reverse string and push to reverseArray
  for (let i = strArray.length-1; i >= 0; i--){
  //loop through string
  for (let j = 0; j < strArray.length; j++){
   //compare at each index the value of the string
    if (strArray[j] != reverseArray[j]){
        return false 
      } else{
        return true


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge Information:

JavaScript Algorithms and Data Structures Projects - Palindrome Checker

A return statement immediately stops the function

Ah okay thanks, so i’m thinking set the result of the if() statement to a result variable and return it outside of the for loop?

let result;
if (strArray[j] != reverseArray[j]){
result = false
} else {
result = true

That way the function doesnt exit immediately when something doesnt match

But then the only value of result that you get is the last one.

Returning early isn’t always a problem. One of those two return statements I quoted is good.

1 Like

Ah okay thank you, think I understand.

Appreciate you taking the time to go through it with me :slight_smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.