Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it correct to use one line for loop in JavaScript without curly brackets? [duplicate]

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.

like image 532
suhailvs Avatar asked Apr 05 '14 03:04

suhailvs


People also ask

Can we use for loop without curly braces?

If the number of statements following the for/if is single you don't have to use curly braces. But if the number of statements is more than one, then you need to use curly braces.

Are braces necessary in one line statements in JavaScript?

No. But they are recommended. If you ever expand the statement you will need them. if (cond) alert("Condition met!") else alert("Condition not met!")

Is there is only one statement inside the loop can we skip the curly braces?

So we can omit curly braces only there is a single statement under if-else or loop. Here in both of the cases, the Line1 is in the if block but Line2 is not in the if block. So if the condition fails, or it satisfies the Line2 will be executed always.

What is the correct syntax for for loop in JavaScript?

for/in - loops through the properties of an object. for/of - loops through the values of an iterable object. while - loops through a block of code while a specified condition is true. do/while - also loops through a block of code while a specified condition is true.


2 Answers

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.

like image 180
ElGavilan Avatar answered Oct 17 '22 12:10

ElGavilan


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.

like image 9
Paul Avatar answered Oct 17 '22 10:10

Paul