0

With this very simple code:

<body>
<script>
  var j;
  j=0;
  do {
    document.write("J="+j+" ");
    j++;
    if (j=4) {
      break;
    }
  }
</script>
</body>

I get an error: Uncaught SyntaxError: Unexpected end of input just at the end of the script. This happens since I'm trying to use break to jump out from the loop.

Of course this is not the code I'm working on, which is way more complicated and needs the break jump. I know in this case a do while loop or for loop would have made it. This is just the smallest code I have showing the error.

Parentheses are balanced, braces are balanced, why does it say it is incomplete?

P.S. I have also tried this very same code as a function, receiving the error Uncaught SyntaxError: Unexpected token } on the brace that closes the function.

2
  • See answer below. Also, if (j=4) { should be if (j==4) {... = is assignment where as == comparison. Commented Apr 9, 2019 at 15:55
  • Yes, thanks. The = Vs. == point get obscured for me 'thanks' to the greater issue of the code not running. JS not my native language. Commented Apr 9, 2019 at 16:03

2 Answers 2

3

do statements in Javascript expect a corresponding while expression.

E.g.

  var j;
  j=0;
  do {
    document.write("J="+j+" ");
    j++;
    if (j=4) {
      break;
    }
  } while (true);

Also worth noting, if (j=4) is always true in JS, you probably meant === for comparison instead of = for assignment. (as Adriani6 mentioned in the comments)

Though, if this is the complete example you're working with, then it would be cleaner to remove the if condition and break as such:

  var j;
  j=0;
  do {
    document.write("J="+j+" ");
    j++;
  } while (j !== 4);

or even easier to read:

for (let j = 0; j < 4; j++) {
   document.write("J="+j+" ");
}
Sign up to request clarification or add additional context in comments.

1 Comment

I already said this is not the complete code I'm working on, so the latter codes don't help me (to my real problem), but It seems you made the point. Thanks.
0
if (j=4) {
      break;
    }

it should be j==4

2 Comments

Should actually be j === 4 ;)
Well yes is more restrictive, also compares the type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.