Structure of if else statment

So I always wondered how important the structure of the symbols were in an if else statement, mainly the brackets { } symbols. For example why can’t you write it or why is it bad practice if at all to write it with them here.

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

versus having them how it’s always shown here

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

It’s just convention, it makes no difference as to how the code works. It makes it easier to follow if everyone’s writing their code the same way.

hope that helps

1 Like

Ok yeah I do think it looks better structurally and prefer I but just always wondered if there was more to it or just for the readability. Thank you.

May be helpful to know that it’s also convention to write if statements inline with their commands if the command is a one-liner and there’s no else or else if to follow. For example, guard clauses are one-liner if statements that return something or break out of a function that are used to reduce the level of indentation in complicated conditional logic structures.

Let’s say I want to do some kind of authorization/authentication procedure and, at every stage, I want to check for some condition. If I use only ifs and elses, the structure will become deeply indented and look confusing and hard to parse, but if I use guard clauses, it will become a lot easier.

// Indentation ■■■■:
if (user) {
    if (user.isLoggedIn()) {
        if (user.isAdmin()) {
} else {

// Guard Clause Bliss:
if (!user) return noUserFound()
if (!user.isLoggedIn()) return goLogInNow()
if (!user.isAdmin()) return youreNotAuthorizedYouSillyBilly()

return index.js

In the second version, we know that if all our guard clauses do not attain, then the user has been authenticated and is authorized to view the content, so we just return the admin page. Because of the guard clauses, there’s no indentation at all, and you can easily parse the content without getting lost in which indentation level you’re currently in and what you’re checking for at that spot.