0

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;
RB.
  • 36,301
  • 12
  • 91
  • 131
Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125
  • If the brackets are not present then it takes immediate line to its for loop. So you have the one line of coding with in the looping or conditional statements then you can omit the brackets. – Dineshkani Mar 07 '13 at 09:26

4 Answers4

2

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

mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

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
Amrendra
  • 2,019
  • 2
  • 18
  • 36
1

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.

Christoph
  • 50,121
  • 21
  • 99
  • 128
1

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.

RB.
  • 36,301
  • 12
  • 91
  • 131