-1

There's a one-lined if/else statement (ternary operations), as seen here.

What about the two-lined ones?

e.g.

if (true) console.log("True");
else console.log("False");

edit: The 'normal' / standard if/else statements I see look like this:

if (true) {
   console.log("True");
} else {
   console.log("False");
}

So the difference: No curly brackets.

lepe
  • 24,677
  • 9
  • 99
  • 108
daCoda
  • 3,583
  • 5
  • 33
  • 38
  • 2
    It's just called `if` statement and `else` statement. Or `if...else` statement as a combined term. – VLAZ Nov 28 '19 at 23:12
  • 2
    You can also put `if`/`else` on a single line or a conditional operator expression on multiple lines, doesn't change anything. – Bergi Nov 28 '19 at 23:16
  • @VLAZ, I've edited my question to provide some clarification; the two lined one is different from the 'standard' if / else statement I have learned and see all the time, as it has no curly brackets. – daCoda Nov 29 '19 at 00:23
  • 1
    @daCoda it doesn't have curly brackets because you don't need them *in this case*. If you don't put brackets, then the next statement belongs to the corresponding block. If you put the brackets in, you are explicitly grouping the statements together. `if (bool) satement1;` will resolve as if you have `if (bool) { statement1; }` - the two are equivalent. The only difference is the coding style. However `if (bool) satement1; statement2;` will resolve as `if (bool) { statement1; } statement2;` hence why most styleguides prefer the brackets, since you can more easily modify the block. – VLAZ Nov 29 '19 at 05:51
  • @VLAZ, cheers, got what I needed, that it's just a coding style. – daCoda Dec 02 '19 at 00:10

3 Answers3

0

The conditional operator, or ternary operator, is called just that - the ternary operator or conditional operator. It is not called a "single-lined if-else statement" because, well, there's no if-else in it. (It might be similar to the effect of an if-else as a single expression, but that doesn't make it one)

The code in your question is just a plain if-else statement, since it uses if-else - no matter how many lines it has.

Snow
  • 3,820
  • 3
  • 13
  • 39
  • 2
    OP is asking about the use of if-else *in comparison to* the conditional operator: *There's a one-lined if/else statement (ternary operations), as seen here.* so I figured it was worth clarifying that the conditional operator is *not* a "one-lined if-else statement". (Rather, anything with `if-else` *is* an if-else statement) – Snow Nov 28 '19 at 23:16
0

Your example is just a standart if-else. The absence of brackets is possible because you have only 1 statment inside the conditions. This can be applied anywhere where you would use brackets to have multiple statments. For example:

while(true) console.log("looping")
0

It's just differences in coding style; see @VLAZ's answer.

daCoda
  • 3,583
  • 5
  • 33
  • 38