Build a Palindrome Checker Project - Build a Palindrome Checker

Tell us what’s happening:

When running the test im getting an error in some parts, for example:

A man, a plan, a canal. Panama.

When copy and pasting that string to the input box in the preview, im getting the output that it is indeed a palindrome, but test its telling me its incorrect, not sure whats happening.

Your code so far

const textInput = document.getElementById('text-input');
const checkBtn = document.getElementById('check-btn');
const results = document.getElementById('result');

let normalizedStringArray;
let isPalindrome = true;

const palindromeChecker = () => {
    if (textInput.value === "") {
        alert('Please input a value');
    } else {
        stringNormalizer();
        for (let i = 0; i < normalizedStringArray.length / 2; i++) {
            if (normalizedStringArray[i] !== normalizedStringArray[normalizedStringArray.length - 1 - i ]) {
                isPalindrome = false;
                break;
            }
        }
        if (isPalindrome) {
        results.innerHTML = `<p class="resultText"><span class="bold">${textInput.value}</span> is a palindrome.</p>`;
        } else {
         results.innerHTML = `<p class="resultText"><span class="bold">${textInput.value}</span> is not a palindrome.</p>`;
        }
        textInput.value = "";
    }


};

const stringNormalizer = () => {
    normalizedStringArray = textInput.value.toString().toLowerCase().replace(/[\W_]+/g, '').split('');
}

checkBtn.addEventListener('click', palindromeChecker);
textInput.addEventListener('keydown', function (e) {
    if (e.key === 'Enter') {
      palindromeChecker();
    }
});

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36

Challenge Information:

Build a Palindrome Checker Project - Build a Palindrome Checker

I’m getting the result:

A man, a plan, a canal. Panama is a palindrome is not a palindrome.

Ahh, I see now. The tests are running your function over and over again to test different strings, so if you have variables in the global scope (outside of a function) then that is going to most likely give you unpredictable results with the tests. With a little bit of testing I’m sure you can figure out which variable needs to be moved inside a function.

Look buddy:

So it happens because of the way test are ran? O: Will check the variables then

Yes, to some extent. But really, this variable should be inside the function it is being used in. In general, if a variable is only being used in one function, then it should be defined inside of that function, not as a global variable.

1 Like

Thanks will keep that in mind, youre correct. Moved isPalindrome to its function and everythings working fine now. :slight_smile:

1 Like