⊗jsPmLpBOP 155 of 504 menu

The Problem with Optional Parentheses in Loops in JavaScript

Although it is possible to omit curly braces in loops, I strongly advise against doing so, as such code often leads to errors.

Let's look at an example. Let's say we have the following code:

for (let i = 0; i <= 9; i++) console.log(i); // will output numbers from 0 to 9

I'll make a small correction to the code above (find which one) - and it will stop working:

for (let i = 0; i <= 9; i++); console.log(i); // will display an error

So what did I fix?

The problem arose because I put a semicolon after the bracket ) from the loop. In this case, you get the so-called loop without a body: it will simply scroll inside, and the next line will no longer apply to it. Therefore, to avoid problems, I always recommend putting curly brackets in loops.

Tell me what the result of running the following code will be:

let arr = [1, 2, 3, 4, 5]; for (let elem of arr); console.log(elem);
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline