Confused about if/else syntax

Hi,
I’m just starting to learn JS and am pretty confused regarding the formatting of if/else statements. For example, why do we prefer:

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

To something like:

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

Both seem to run properly (at least simple ones do!), but the second option both uses less lines and seems much more readable to my eye (could even indent else for further readability). Why is the first option preferred, does it have something to do with the function of the curly brackets?

Thanks!

1 Like

Hi,

Welcome to the Codecademy forums!

You’re correct in noticing that both pieces of code work perfectly fine. The JavaScript interpreter does not care how the code is formatted because it ignores most of the white space.

The first option is generally used because most people find it easier to read, especially when it comes to scripts that are much longer. Whilst you may find the second option much more readable, it is useful to be able to write code that is formatted in a way that helps other developers to read your code.

For personal projects, you can use whatever format you prefer. But when posting code on the forums or when collaborating with others, I would suggest following the standard way of formatting JS to avoid mistakes and confusion.

Hope that helps!

1 Like

Thanks for the fast response!

Exactly, if working with other people I want to understand and know the standards that are used; that’s very important I think.

I’m just totally not understanding yet how it is easier to read, maybe it would help if I had the perspective of someone who does prefer the first option (if I can’t figure out the logic, I think I will never remember!). Is it glance value?

2 Likes

It becomes a much more important factor as your programs get larger. You may well find you can just put a single if statement on one line, but in real-world programs, the code is much longer and more involved. You may have a large amount of tasks that get performed inside the if statements. You may also have other if statements.

Having a separate line where you can see the start of the if statement can make things far more readable. You will also have everything inside that if statement indented, so you can see at a glance how much of the code is inside the if statements.

1 Like

Thanks for the response, in that case I guess I will just carry on until things start to get more complex and hopefully then I will see the advantages :smiley:

1 Like

ok so say if there us a sale u would want to buy and say Time to Buy stuff but if there is not a sale time to wait for a sale

but ur second statements is the same thing just more compact u can use compact stuff like this if u have tim on ur hands and want to add a quick statements

hope this helps