Why does a for loop with a semicolon after it still execute?

前端 未结 4 1602
离开以前
离开以前 2020-12-21 13:42

I was having a look at some code a friend did and stumbled across this line which I thought was an error (simplified for example)..

for (g = 0; 10 > g; g+         


        
相关标签:
4条回答
  • 2020-12-21 14:14

    As far as I know this is simply a syntax feature of the language. Basically, javascript ignores that semicolon.

    EDIT: Sorry, misread your post. If you mean that you only get alerted once, then you have basically an empty loop executing ten times, then a single block of code containing the alert executing once.

    Accolades ({...}) can go around any block of code, independent of constructs such as for-loops.

    0 讨论(0)
  • 2020-12-21 14:26

    Your g variable is within the global context, so it is accessible outside of a for loop. The loop did its job, and incremented g 10 times.
    Two {} indicate a block in JavaScript and won't cause any error.

    Edit: it is not alerting anything without a for loop, because the g variable is not defined.

    0 讨论(0)
  • 2020-12-21 14:31

    The semi colon actually runs the loop without the {} code block. So your code basically has 2 parts,

    1. update variable g to from 0 to 10 in 10 steps,
    2. print out g (now equals to 10) once.
    0 讨论(0)
  • 2020-12-21 14:39

    your for loop runs 10 times but wont alert anything since you have put ;

    that alert you are getting is only once because of that statement outside of for loop

    0 讨论(0)
提交回复
热议问题