Clean up your code with these tips!
Tags: discuss, tips, javascript, tutorial
Published: 2019-02-05 06:28:03

---
title: Clean up your code with these tips!
published: true
description: Learning new patterns to make your code smaller, and more clear.
tags: discuss, tips, javascript, tutorial
---

## TL:DR

See bottom;

## The breakdown

After reading the discussion <a href="https://dev.to/tyrw/ifelse-or-just-if-1kie" target="_blank">If/else or just if?</a>, it made me think that it might be helpful for some of you, for me to share a few patterns I like to follow that helps me keep my code smaller and cleaner.

It's so easy to stick to the patterns/styles of coding that you're used to or that you learned from the very beginning. This will hopefully challenge you to see if you can improve.

I'll walk you through a typical scenario and how to clean it up, by using an example from a recent piece I was working on. 

Here is how you might see some developers write it.

*Note:* I'm coding in es6 for the example. 


My code needs to confirm hostname is available, check if it's a localhost site I'm working with and if so then set my cookies to non-secure. This is required because otherwise, chrome and some other browsers will not allow cookie storage via localhost when marked as secure. See here <a href="https://stackoverflow.com/a/11957810/11016029" target="_blank">buried deep down in the stackflow</a>


```javascript
let secure;

// Check if window.location.hostname is set.
if (
    typeof window !== 'undefined'
    && window.hasOwnProperty('location')
    && window.location.hasOwnProperty('hostname')
) {
    const domain = window.location.hostname;
     
    if (domain == "localhost" || domain == "127.0.0.1") {
        secure = false;
    } else {
        secure = true;
    }
} else {
    secure = true;
}

export default new Cookie({secure: secure});
```

Now a few things you might notice right off the bat. Such as getting rid of both the "else" statements by setting the top `let secure` to `let secure = true`. 

How about the use of <a href="https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthand" target="_blank">property value shorthand</a>? `{secure: secure}` now becomes `{secure}`.

```javascript
let secure = true;

// Check if window.location.hostname is set, 
if (
    typeof window !== 'undefined'
    && window.hasOwnProperty('location')
    && window.location.hasOwnProperty('hostname')
) {
    const domain = window.location.hostname;

    if (domain == "localhost" || domain == "127.0.0.1") {
        secure = false;
    } 
}

export default new Cookie({secure});
```

We cleaned it up a bit, but we can definitely do better. Any time you see a sub "if" statement, you should ask yourself "how can I clean this up?". It's rare you need to have sub "if" statements if you know how to avoid them.

Let's first break the sub "if" statement out and put it below the main "if" statement.

We can do that by initializing our "domain" variable above to "null" or "false" (I prefer null, feel free to discuss), then set the domain to the hostname if it's available via window.location.hostname.

Next, we update our sub "if" to now check for "domain" having a <a href="https://www.sitepoint.com/javascript-truthy-falsy/" target="_blank">truthy</a> value on top of the original check against localhost/127.0.0.1.

That reminds me, lets clean up that check for the localhost/127.0.0.1 with some regex. `domain == "localhost" || domain == "127.0.0.1"` now becomes `/^(localhost|127\.0\.0\.1)$/.test(domain)`

If you don’t like regex, you can use this smooth tip from [vojtechp](https://dev.to/vojtechp?utm_source=notify_mailer&utm_medium=email&utm_campaign=new_reply_email) to make it even easier to read. 

```javascript
const localDomains = [ 'localhost', '127.0.0.1' ];
const isLocal = domain && localDomains.includes(domain);
```

or you could do a cleaner version mentioned by [miniscruff](https://dev.to/miniscruff) with `Set`

```javascript
const localDomains = new Set([ 'localhost', '127.0.0.1' ])
const isLocal = localDomains.has(domain)
```

If you're wondering why you should declare variables before using them, read <a href="https://www.w3schools.com/js/js_best_practices.asp" target="_blank">Always Declare Local Variables</a>.

This leaves us with the below.

```javascript
let secure = true;

// Declared domain variable as a let
let domain = null;

// Check if window.location.hostname is set, 
if (
    typeof window !== 'undefined'
    && window.hasOwnProperty('location')
    && window.location.hasOwnProperty('hostname')
) {
    domain = window.location.hostname;
}

// Moved out and now checks additionally "domain" is set
if (domain && /^(localhost|127\.0\.0\.1)$/.test(domain)) {
    secure = false;
} 

export default new Cookie({secure});
```

Hopefully by now you're starting to see how each time, we improve the code a little more. 

So how far can we take this? Let's see what else we can do.

One major improvement to my coding style, I learned off of a random blog. I really wish I could give them credit, but unfortunately it was so long ago, I forget who it was. 

What they showed was to move the logic out of if statements and assign them to variables, when it involves 2 or more values. I'll have to write up another post about this, as you can get really creative with it, but for now we'll keep it simple.

So we now would go from 

```javascript
if (
    typeof window !== 'undefined'
    && window.hasOwnProperty('location')
    && window.location.hasOwnProperty('hostname')
) 
```
to
```
const hostnameAvailable = typeof window !== 'undefined'
    && window.hasOwnProperty('location')
    && window.location.hasOwnProperty('hostname');
```

Where the power lies in this, is that you can start to clean up your if statements to be more readable, or even move away from them all together (within reason).

So knowing this new trick we move forward with that in mind.

If you are paying close attention, you will see we are building the "if" statements, off of each other... So it feels like maybe we could take advantage of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator" target="_blank">Ternary Operator</a>.

Combine the new trick we learned about moving out the "if" logic to variables, with ternary and you can do this! 

```javascript
let secure = true;

const hostnameAvailable = typeof window !== 'undefined'
    && window.hasOwnProperty('location')
    && window.location.hasOwnProperty('hostname');
const domain = hostnameAvailable ? window.location.hostname : null;
const isLocal = domain && domain.match(/localhost|127\.0\.0\.1/);

if (isLocal) {
    const secure = false; 
}

export default new Cookie({secure});
```

But, DeChamp... that "if" statement! Oh right, we can fix that too. Take advantage of flipping truthy/falsy with <a href="https://www.sitepoint.com/javascript-double-negation-trick-trouble/" target="_blank">logical not "!"</a>. Take a look at the double logical not, on that same page as well.

```javascript
const hostnameAvailable = typeof window !== 'undefined'
    && window.hasOwnProperty('location')
    && window.location.hasOwnProperty('hostname');
const domain = hostnameAvailable ? window.location.hostname : null;
const isLocal = domain && /^(localhost|127\.0\.0\.1)$/.test(domain);
const secure = !isLocal;     

export default new Cookie({secure});
```

Wow, that looks so much better! 

## Wrap up

- We learned that declaring variables with values up top, can help eliminate "else" statements.

- Breaking out sub "if" statements. 

- Moving out the "if" logic to variables, and then using ternary, can help make it easier to read and chain together.

- Regex allows further clean up, when doing multiple checks on a single variable.

- Using "not" operator to flop boolean values.

## More tips!

```javascript
// instead of this
if (foo === 'a') {
    bar = 'first';
} else {
    bar = 'second';
}

return bar;


// use return to clean it up!

if (foo === 'a') {
    return 'first';
}

return 'second';

```

```javascript
// instead of this

const foo = bar ? bar : baz;

// do this
const foo = bar || baz;
```


This one was provided via user <a href="https://dev.to/kayis" target="_blank">Kayis</a>

```javascript
let secure = true;

try {
  secure = !window.location.hostname.match(/localhost|127\.0\.0\.1/);
} catch (e) {}

export default new Cookie({ secure });
```

**Add yours in the comment and I'll add them here and give you credit!**



## TL:DR

from 

```javascript
let secure;

// Check if window.location.hostname is set.
if (
    typeof window !== 'undefined'
    && window.hasOwnProperty('location')
    && window.location.hasOwnProperty('hostname')
) {
    const domain = window.location.hostname;
     
    if (domain == "localhost" || domain == "127.0.0.1") {
        secure = false;
    } else {
        secure = true;
    }
} else {
    secure = true;
}

export default new Cookie({secure: secure});
```

to 

```javascript
const hostnameAvailable = typeof window !== 'undefined'
    && window.hasOwnProperty('location')
    && window.location.hasOwnProperty('hostname');
const domain = hostnameAvailable ? window.location.hostname : null;
const isLocal = domain && /^(localhost|127\.0\.0\.1)$/.test(domain);
const secure = !isLocal;     

export default new Cookie({secure});
```

## Followup

I really hope you learned some new tricks. It can be a lot of fun to see how small and clear you can get your code. I wouldn't be surprised if some of my smart readers, teach me even more tricks!


Did you like my post? Have questions? Did I miss something or make a mistake? Let me know!

--DeChamp


---

Varymade LLC.

Current projects are https://charactergenerator4000.com and https://coder.exchange. Please check them out and let us know your thoughts.