Tithos
Tithos

Reputation: 1437

Palindrome program - unexpected identifier error

I am trying to write a JS program to print the largest palindrome between 1 and 1000 (929). I am getting an Uncaught SyntaxError: Unexpected identifier on line 4 of my code:

    var num = 1;

    for (var i=0;i<=1000;i++) {
      if i == reverse(i) && isPrime(i)
          num = i;
          console.log(num);
    }
    document.write(num);

    function reverse(s) {
        var o = '';
        for (var i = s.length - 1; i >= 0; i--)
            o += s[i];
      return o;
    }

    function isPrime(number) {
        var start = 2;
        while (start <= Math.sqrt(number)) {
            if (number % start++ < 1) return false;
        }
        return number<=1 ? false : true;
    }

What is an Uncaught SyntaxError: Unexpected identifier? And how do I fix the bug?

Upvotes: 0

Views: 373

Answers (2)

noodle71
noodle71

Reputation: 94

I think that you missed two brackets inside the for loop but also I think that you have an error in your "reverse" function. Try this solution:

var num = 1;

function isReversible(s) {
    var o=s.toString();
    return o.split("").reverse().join("")==s.toString()?true:false;
}

function isPrime(number) {
    var start = 2;
    while (start <= Math.sqrt(number)) {
        if (number % start++ < 1) return false;
    }
    return number<=1 ? false : true;
}

for (var j=0;j<=1000;j++) {
    if (isReversible(j) && isPrime(j))
      num = j;
    console.log(num);
}
document.write(num);

Upvotes: 0

samrap
samrap

Reputation: 5673

Your if statement is missing parenthesis () and block identifiers {}.

The syntax for a JavaScript if statement is as follows:

if (condition) {

    // do something

} else {

    // do something else
}

So, change your if code above and you should be good!

Upvotes: 3

Related Questions