# Loop not working or unexpected result

Tell us what’s happening:

Your code so far

``````
function checkP(num){
var result= true ;
var  str = num.toString();
//  console.log(10**3)
for (let i=0; i <str.length; i++){
if ( str[i] === str[str.length-1-i]){

} else {
result = false ;
}
}
return result ;
}
console.log(checkP(9702))
var prod =1 ;
var num = 99 ;
var number  = 11;
function largestPalindromeProduct(n) {
var lN = 10**n ;
for (let i = lN-1; i >0 ;i--  ){
prod = i*num ;
num = num - 1 ;
if (checkP(prod) === true){
break;
}
number = prod ;
//return number ;
}
return number ;
}
largestPalindromeProduct(2)
console.log(largestPalindromeProduct(2));
//console.log('101'[2]==='101'['101'.length-1-2])
``````

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

Challenge: Problem 4: Largest palindrome product

Link to the challenge:

A couple of things I spotted.

`num` is defined outside of your function. So running the function multiple times will give a different result, since you change the function’s value inside of the function itself. The same goes for `number`. You shouldn’t set it to 11. In computer programming, palindromes can be one letter. So technically, the smallest palindrome is 0. Still, number should be defined as a local value inside of the function itself.

On to the function, the reason you’re getting a weird result is of how you assign product to number. You have `checkP` to let you know if you’ve found a palindrome. But then you break the loop without ever assigning said palindrome to number. Actually, your code will assign product’s value to `number` in every iteration of the loop, which probably isn’t what you want. So upon finding a palindrome, the loop breaks and returns number, regardless of what number’s last value was.

In your loop, you also decrement `i` and `num` at the same time. I wouldn’t recommend doing this since you skip over some results. A nested for loop might serve you better.

Finally, I’ll warn you. Reading this post caused me to attempt that Euler problem myself. The first valid palindrome you find is not always going to be the largest palindrome. You can’t return the first palindrome you get because it may not be the right answer.

1 Like