I am having trouble understanding the usage of brackets in \"for\" loops and \"if\" statements in Javascript. I have seen syntax in Javascript where there is brackets and where
You can omit the brackets when the for
loop applies to a unique statement.
You must use it if you want it to apply to more statements. To be more precise, the for
loop always apply to a statement but the brackets build a block which is a statement.
Adding the brackets, when there is only one statement, can't break the code and often makes it more readable. In fact most coders won't go to the next line in an opening for
loop without brackets. I personally would replace
for (var i = 0; i <= upto; i++)
result[i] = i;
with
for (var i = 0; i <= upto; i++) result[i] = i;
or
for (var i = 0; i <= upto; i++) {
result[i] = i;
}