Search code examples
javascriptcurly-brackets

for next loop brackets in javascript


I recently found this bit of JavaScript code (which is fine functionally) but I noticed that they're were no brackets around the for next loop. I always thought you must include them for the code to function. Under what conditions can you omit the brackets and still get away with it? Functionally, that is, not aesthetically.

for (var i = 0; i < rbuttons.children.length; i++)
    if (rbuttons.children[i].value == true)
        return rbuttons.children[i].text;

Solution

  • Brackets are not mandatory for one statement only. Good practice but not mandatory

    so

    if (x) alert("x");
    

    or

    if (x) 
       alert("x");
    

    will work

    In your case

    if (rbuttons.children[i].value == true) return rbuttons.children[i].text;
    

    is one statement