How to Write Cleaner If Statements In JavaScript
Tags: webdev, codenewbie, javascript, beginners
Published: 2020-07-17 20:38:23

One of the major abilities we have when writing code is to write so things happen conditionally. When talking about conditional code, often we are talking about good ol' if else statements 👍🏾. If you haven't come across if else statements yet that's totally okay! You can think of them as a way to make different things happen depending on whether something is true or false. In JavaScript, if statements look something like this: 

```javascript
let isCold = true;
if (isCold === true) {
	console.log("Turn up the heat 🥶!");
} else {
	console.log("It's nice and hot ☀️😎.");
}
```

In the example above, you can see that something different will get logged to the console depending on the variable isCold being true or false. Now, imagine if you need if you needed to check more complex conditions. Once you do, your if statements could get longer and nested like this one:

```javascript
let isMilkSmelly = false;
let isMilkExpired = false;
let isHavingCereal = true;

if (isMilkSmelly === true) {
    console.log("Ewww 😷");
    if (isMilkExpired === true) {
        console.log("Time for the trash 🗑");
    }
} else if (isHavingCereal === true) {
    console.log("Yay for not smelly milk!");
} else {
    console.log("I just wanted waffles.");
}
```

You might find the above example not that bad, but you can imagine all of the micro-decisions we make when making bigger decisions. One example could be imagining the if else statements you'd need to evaluate a poker hand.

With that in mind, there are many ways to make your if statements look cleaner and we're going to look at some now!

### TLDR
*Guard Clauses*: Guard Clauses are a way to write if statements that allow us to guard the flow of logic depending on whether a condition is met. Usually this is done by returning after a statement so the function stops when a condition is met. It's beneficial because it allows us to avoid nested if statements.

``` javascript	
function getTemperature() {
    return 25;
}

function getBlanket() {
    if (getTemperature() <= 20) return true;
    if (getTemperature() > 20) return false;
}

console.log(getBlanket()) // false
```

*Ternary Operator*: The ternary operator is like a shorthand for writing if statements! It has three parts, part one is the condition followed by a question mark, part two is what should happen if the condition is true follow by a colon, and part three is what should happen if the condition is false. Here is an example:

```javascript	
function getTemperature() {
    return 25;
}

function getBlanket() {
    return (getTemperature() <= 20) ? true : false
}

console.log(getBlanket()) // false
```

*Syntax Tips*: There are some cleaner ways that JavaScript gives us out of the box to write if statements. Here are some examples:

``` javascript
let isMilkSmelly = false;
let isMilkExpired = false;
let isHavingCereal = true;
	
// If statements in one line
if (isMilkSmelly === false) { console.log("Yes, it stinks 😷!") }
	
// With no keyword the if statement will check if the value is true
if (isHavingCereal) { console.log("Yes, let's have some cereal!") }
	
// If statement without curly brackets
if (isHavingCereal) console.log("Yes, let's have some cereal!");
	
// Check if condition is not true without false keyword
if (!isMilkSmelly) console.log("Yes, it stinks 😷!");
	
// Check If else & else-if in one line without curly brackets.
if (isMilkSmelly) console.log("Yes, it stinks 😷!")
else if (isMilkExpired) console.log("No, it's gone bad!")
else console.log("Yes, let's have some cereal!");
```


# Making Your If Statements Cleaner

## Guard Clauses
In JavaScript we use the return keyword to send data out of our functions, kind of like hitting the eject button. If we combine that functionality with if statements we can get a pattern called Guard Clauses. These guard clauses allow us to write more concise if else statements, which makes our code cleaner and easier to read. They help us clean up our if else statements by allowing us to avoid nested if statements. There is nothing inherently wrong with nested if statements; I've used them tons! However, once I learned about guard clauses I figured why not have my if statements be a little cleaner 🧼 where I can. To make this a little clearer, why don't we look at an example.

```javascript
	// Without Guard Clause - 9 Lines
	function getBlanket() {
		let isCold;
		if (getTemperature() <= 20) {
			isCold = true;
		} else {
			isCold = false
		}
		return isCold;
	}
	
	// With Guard Clause - 4 Lines
		function getBlanket() {
			if (getTemperature() <= 20) return true;
			if (getTemperature() >= 20) return false;
		}
```

Isn't that super cool! When I discovered guard clauses the idea blew my mind for a minute 🤯. Code can get really complex when it comes to conditions, and guard clauses are just one way to make things easier on ourselves. 

## Ternary Operator
I promise the hardest thing about the ternary operator is saying the word ternary 😄 (tur-nr-ee according to Google 🤔; always gives me trouble 😅). The tur-nr-ee operator allows us to write if else statements in a single line.  Let's look at an example. 

``` javascript
	let isCold = true;
	
	// Valid Ternary Operator - check is true
	isCold ? console.log("🥶🧊") : console.log("🥵🌞");
```

Here is a visual example that labels the different parts!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1aad4p8lthwvzmckd64s.png)

With the anatomy in mind, another cool fact about ternary operators is that you can chain them like if else-if statements! Let's take a look: 

``` javascript
	let isMilkSmelly = false;
	let isMilkExpired = false;
	let isHavingCereal = true;
	
	isMilkSmelly ? console.log("Yes, it stinks 😷!")
	: isMilkExpired ? console.log("No, it's gone bad!")
	: isHavingCereal ? console.log("Yes, let's have some cereal !") 
	: console.log("Let's have pancakes!");
```

These chained ternary operators work like if else-if blocks, but since you can write each condition as it's own line it can make your code cleaner and easier to parse. 

I think the ternary operator is a great tool to have in your programmer tool belt. They give us a quick and clean way to write our if else statements. However, with its coolness there are some things to keep in mind. For instance, you can't do something like this: 

``` javascript
let isHavingCereal = true;
isHavingCereal ? return console.log("I want cereal!") : return console.log("I want waffles!");
```

If you're asking why you can't do this, don't worry because I thought the same thing. The reason you can't do this is because anything after the first return in this statement would be considered unreachable code. If you ran this code you'd get an error saying "Uncaught SyntaxError: Unexpected token 'return'".

## Syntax Tips
Along with the two methods we've talked about so far, there are some general syntax tips we can keep in mind to make our if statements cleaner. We've already seen some of these in our previous examples but let's look at them here to be explicit. 

``` javascript
let isMilkSmelly = false;
let isMilkExpired = false;
let isHavingCereal = true;
	
// If statements in one line
if (isMilkSmelly === false) { console.log("Yes, it stinks 😷!") }
	
// With no keyword the if statement will check if the value is true
if (isHavingCereal) { console.log("Yes, let's have some cereal!") }
	
// If statement without curly brackets
if (isHavingCereal) console.log("Yes, let's have some cereal!");
	
// Check if condition is not true without false keyword
if (!isMilkSmelly) console.log("Yes, it stinks 😷!");
	
// Check If else & else-if in one line without curly brackets.
if (isMilkSmelly) console.log("Yes, it stinks 😷!")
else if (isMilkExpired) console.log("No, it's gone bad!")
else console.log("Yes, let's have some cereal!");
```

# Well That Was Fun 😄
There we have it! Guard Clauses, the Ternary Operator and some quick syntax tips. Hopefully you find these useful (and cool 😎) on your journey. 

Happy Learning 😄👋🏾!