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.
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.
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!")
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With