See bottom;

The breakdown

After reading the discussion If/else or just if?, 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 buried deep down in the stackflow



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 property value shorthand? {secure: secure} now becomes {secure} .



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 truthy 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 to make it even easier to read.



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

or you could do a cleaner version mentioned by miniscruff with Set



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 Always Declare Local Variables.

This leaves us with the below.



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



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 Ternary Operator.

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



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 logical not "!". Take a look at the double logical not, on that same page as well.



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!

// 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 ' ;

// instead of this const foo = bar ? bar : baz ; // do this const foo = bar || baz ;

This one was provided via user Kayis



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!

from



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



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