Question

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;
Was it helpful?

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

OTHER TIPS

You can omit the brackets if you only have one statement.

if (someTest)
statement1;
statement2;

is equivalent to

if (someTest)
{
    statement1;
}
statement2;

Please note that it is considered best practice to always include the brackets.

It's the same as with if. The next statement counts as member of the for loop.

for( var i = 0; i<10;i++)
console.log(i);
console.log("foo");
// prints 0-9 but "foo" only once

Since the if in your code has only the return statement bound to itself and the if itself is bound to the for, you can omit the braces for both in this snippet.

Sloppy and error-prone style and absolutely not recommended.

If no brackets 'for' and 'if' consider only next statement.that's why your code is running.give one more statement after for and check,your code will not work.

var y=2;
var x=0;
for(i=0;i<10;i++)
 x+=i;//inside loop
 y+=i;//not inside loop


if(y)
x=5;//work according to if condition
y=10;//not work according to if condition
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top