Petros Koulianos

Posted on

# 2 Tips to Clean Ugly if Statements

Conditional statements are the backbone of programming but lot of times business requirements can lead to create long nested and ugly if statements.
This post demonstrates some tips to clean those ugly situations.

# #1 Complex condition expressions

Long and complex condition expressions are obvious an ugly situation

``````// weird π£π£
if((temp === 0) || (temp > 0 && temp < 5 && gusts > 10) || (snowing)){
//code block
}
``````

Solution create a separate function to return a boolean that represents the long condition

``````// better ππ
if(isColdOutside(temp, windGusts, snowing)){
//code block
}

function isColdOutside(temp, windGusts, snowing){
if(temp === 0){
return true
}
if(snowing){
return true
}
if(temp > 0 && temp < 5 && windGusts > 10){
return true
}
return false
}
``````

# #2 Ternary into ternary

This is another situation that is ugly and the human brain struggle to parse

``````// weird π£π£
let temp = 6
let windGusts = 20
let isFreezingOutside = temp < 5 ? (windGusts > 15 ? true : false) : (snowing ? true : false)
``````

Solution again here we can create smaller functions to make it cleaner

``````// better ππ
let temp = 6
let windGusts = 20

let isFreezingOutside = temp < 1 ? isSnowing(snowing) : isWindStrong(windGusts)

function isWindStrong(windGusts){
if(windGusts > 15){
return true
}
return false
}

function isSnowing(snowing){
if(snowing){
return true
}
return false
}
``````

This was two quick tips to clean ugly if statements.

Tirtha Guha

For #1 Complex condition expressions
I would prefer writing the complex condition, as it is simpler than 3 if statements.

``````function isColdOutside(temp, gusts, snowing){
return ((temp === 0) || (temp > 0 && temp < 5 && gusts > 10) || (snowing))
}
``````

amiceli

Another tips I use :

``````if (a === "test" || a === "foo") {}
``````

Better I think :

``````if (["test","foo"].includes(a)){}
``````
DEV Community

## 11 Tips That Make You a Better Typescript Programmer

### 1 Think in {Set}

Type is an everyday concept to programmers, but itβs surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

### #2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

...