What is the formatting for if/else statements? (Semicolons and indentation)

i have a question on the if…else statement …why we didn’t put a semi-colon after the code block of else statement for example:

if (sale) {
console.log(‘Time to buy!’);
} else {
console.log(‘Time to wait for a sale.’)
}
*I meant after the last parentheses of else …
why didn’t we write it as
else {
console.log(‘Time to wait for a sale’);
}

1 Like

Semi-colon tells the interpreter to stop parsing and begin compiling. An if statement does not end untl after the else block. Even then we don’t give it a semi-colon since it is well delimited and the interpreter knows to parse from if to the final }.

The statements inside the blocks may well need a semi-colon, though we might be able to relax that requirement when there is but one statement in the block. Newer iterations of JS in most browsers will auto-insert them but we should not depend upon this a reliable feature.

15 Likes

if (false) {
console.log(‘The code in this block will not run.’);
} else {
console.log(‘But the code in this block will!’);
}

In the above snippet, why is the else statement indented with the if statement? Shouldn’t they be on the same ‘level’ as in aligned vertically?

From my understanding of doing a bit of research into the topic is that it is both a personal choice and assists with readability.

You could write that code as:

if (false) {
console.log(‘The code in this block will not run.’);
} 
else {
console.log(‘But the code in this block will!’);
}

The above would work exactly the same way, but when you start nesting if statements in other if statements, it makes it more readable if you indent the else statement after the if, as when you are reading it, you will immediately know that that else statement belongs to that if statement, where if you do it the way I showed above, it might take a little more investigation to find out which one it belongs to.

8 Likes

If it is just a matter of readability, personally I find doing it the following way a lot better for knowing what belongs where at a glance, even if it uses more lines:

if(sale) 
{
  console.log('Time to buy!');
} 
else 
{
  console.log('Time to wait for a sale.');
}

Especially in text editors where you can fold curly bracket contents, I find it really helps, especially for nested conditionals. Apparently I must be in the minority from what I read everywhere. My question is: would this different preference somehow hamper my eligibility or ability to work in a team?

2 Likes

Thank you!

Beautifully explained.

1 Like