18

I am familiar with one line if statement, i found it here and here:

if (x==0) alert('zero');

Is it correct to use for loop one line:

for (var i=0; i < 3; i++) alert(i);

this fiddle works just fine.

Community
  • 1
  • 1
suhailvs
  • 20,182
  • 14
  • 100
  • 98
  • @thefourtheye but i googled it. not found anywhere mentioning it. every where using the `{`. – suhailvs Apr 05 '14 at 03:48
  • 4
    Using braces after your `for` or `if` statement is safer against accidental coding errors and less likely for someone modifying/maintaining your code to make a mistake too. It is not required, but just because something isn't required doesn't mean it's a best practice. Semicolons at the end of a statement are often not required either, but it's a better practice to use them. – jfriend00 Apr 05 '14 at 03:49
  • @Paul - yeah, this seems to me to be a dup of that one. – jfriend00 Apr 05 '14 at 03:52
  • 1
    I always avoid this sort of thing. It'll run, but you never know how someone will read it somewhere down the line - think Apple's `goto fail` bug. – rickcnagy Apr 05 '14 at 04:07
  • 1
    This is technically valid, but I would say it's a bad idea. I would *never* put something like that in my own code. One of the best habits I ever learned was to *always* use braces for all for/if/while/switch statements. – jahroy Apr 05 '14 at 04:34

2 Answers2

16

Both methods are valid in Javascript.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Statements

All Javascript cares about is what is immediately after the for statement. It can be a statement block (multiple statements in curly brackets) or a single statement.

This is true for nearly every control statement in Javascript.

ElGavilan
  • 6,610
  • 16
  • 27
  • 36
9

Yes, it is correct to only have one statement there. In fact, it is required by the language. A for statement has the syntax:

for (ExpressionNoIn ; Expression ; Expression) Statement 

notice that it only includes only one Statement.

A block is a type of statement which is defined using curly brackets and contains a StatementList, so you can use a block for that statement, which is what you see when there are curly brackets.

You can also use any other statement there; it doesn't have to be a block statement.

Paul
  • 139,544
  • 27
  • 275
  • 264
  • I often see code golf like this `function norm2(a) {var sumsqr = 0; for (var i = 0; i < a.length; i++) sumsqr += a[i]*a[i]; return Math.sqrt(sumsqr);}` – dcsan Sep 02 '18 at 18:19