Home > Back-end >  Significance of ';' after for loop condition in JS
Significance of ';' after for loop condition in JS

Time:05-07

const arr = []
for(let i=0 ; i<=5 ; i   );{
  arr.push(i)
 }
console.log(arr)

Can anyone explain me this scenario ?

CodePudding user response:

I just rewrite above code. In for loop i will be increase from 0 to 5, when i reaches to 6, it will be return through i<=5. and push 6 to arr. that's it.

const arr = []
for(var i=0 ; i<=5 ; i  ) {  // i will be from 0 to 6.
  arr.push(i)
}
console.log(arr) // [6]

CodePudding user response:

The semicolon between round bracket and curly stops the statement.

CodePudding user response:

You can do the following:

  • If you are trying to push the numbers 0 to 5 into the array, then remove the semicolon (;), else it will cause reference error since i is a let variable.
  • If you want to push only the last value of i (which is 6) then please use var instead of let inside for loop.
  • Related