'Significance of ';' after for loop condition in JS
const arr = []
for(let i=0 ; i<=5 ; i++ );{
arr.push(i)
}
console.log(arr)
Can anyone explain me this scenario ?
Solution 1:[1]
The semicolon between round bracket and curly stops the statement.
Solution 2:[2]
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]
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mounish |
| Solution 2 | |
| Solution 3 | smabrar |
