Angular / TypeScript: 10 Tips to Avoid If/Else Structures in Your Code

Amine Souissia
5 min readOct 29, 2023

Hello Everyone,
This is my first article on Medium, I hope you like it !
Today I’m going to show you 10 ways to improve your code and factor your If/Else structures, let’s get started !

Replace if/else with a Mapping Object

Here we are going to replace our if..else with a mapping object, as we can see in the example below, so rather use if..else and directly return access to the correct index in relation to your object mapping

// before
getNumber(name) {
if (name === 'BMW') {
return 1;
} else if (name === 'MERCEDES') {
return 2;
} else if (name === 'AUDI') {
return 3;
} else {
return null;

// after
getNumber(name) {
const numberMapping = {
'BMW': 1,
'MERCEDES': 2,
'AUDI': 3,
};
return numberMapping(name) || null ;
};

Replace if/else with a Filter

Let’s imagine that you have a simple loop that you go through and in the processing of this loop you have an if which also includes a processing.

So what you are doing below is that you are iterating on a list where you’re not entirely interested by its elements since you’re putting an if structure, so what you can do here is

// before
userList.forEach(user => {
if(user.isConnected) {
redirectToHome();
}
});

// after
userList
.filter(user => user.isConnected)
.forEach(_ => redirectToHome(););

Replace if.. else with substitute algorithm

We can understand the code below for the moment but imagine if we had around thirty cases to test, it will surely be unreadable. The solution is to use the replacement algorithm which comes from the refactoring book by Martin Fowler and which consists of replacing code with an algorithm

// before 
if (user.id =='1' || user.id =='2' || user.id =='3' || user.id =='4') {
user.role= 'admin';
}

// after
const usersWithAdminRole = ['1', '2' , '3','4'];
if(usersWithAdminRole.includes(user.id)) {
user.role= 'admin';
}

Replace if.. else with condition

Now we move on to the case where we have if .. else which returns a boolean, if this condition is true return true otherwise return false! So you can just return the condition like below

// before 
userWithAdminRole(user) {
if (user.id =='1' || user.id =='2' || user.id =='3' || user.id =='4'){
return true;
} else{
return false;
}
}

// acceptable
userWithAdminRole(user) {
return (user.id =='1' || user.id =='2' || user.id =='3' || user.id =='4'){
}

// more acceptable
userWithAdminRole(user) {
return ['1', '2' , '3','4'].includes(user.id);
}

Replace if/else with a Null Coalescing Operator

Below we move on to a very classic case, we have an if..else which first assigns you an exists property otherwise we assign it a default value!
there we can already delete the if..else like this

// before
let age;
if(response.data.age) {
age = response.data.age;
} else {
age = 'Age could not be determined';
}

// after
const age = response?.data?.age ?? 'Age could not be determined'

Replace if/else with Variable Extraction

When you have a condition that starts to become unreadable and you have more than 3 elements to test you can do a Refactoring from Martin Fowler book which is simply consists to extract a variable and give a name to the processing that you are doing.You can do it as many times as you want

// before
if(isLoading && deleteElement !== undefined
|| (user.isConnected && user.element === null)) {
// do somthing
}

// after
const isLoading = ...;
const isUserConnected = ...;
const isCardEmpty= ...;

const isUserCanBuy = isUserConnected && isLoading && !isCardEmpty;

if(isUserCanBuy) {
// do somthing
}

Replace if/else with Polymorphism

Here we will use polymorphism instead of if..else, as we can see in the example below where we ask the price of a book and depending on the type of book I will do several if..else

What we could do below is to write a class by type of book which will be responsible for calculating the price

// before 
getPrice(book) {
switch(type) {
case PaperBook:
return book.basePrice;
case EBOOK:
return (book.basePrice - 5.90) * 0.75;
case AudioBook:
return book.basePrice * 0.5;

// after
abstract class Book {
// declare somthing
abstract getPrice() : number;
}

class PaperBook extends Book {
getPrice(): number {
return getBasePrice();
}
}

class EBook extends Book {
getPrice(): number {
return (getBasePrice() - 5.90) * 0.75);
}
}

class AudioBook {
getPrice(): number {
return getBasePrice() * 0.5;
}
}

Replace if/else with Boolean Constructor

In the case below we will test the user at the isLoggedIn property and return true or false.
Be careful to not replace with the chaining operator “?” because it’s not going to work since the “?” if it does not find the path to isLoggedIn it returns undefined so there are 3 true values (true, false and undefined).
The best way to factor is to use the JavaScript ball constructor which is applied using “!!”
So if we apply the boolean constructor I will transform the 3rd “undefined” value into false

// before
if(user?.isLoggedIn) {
return true;
} else {
return false;
}

// do not do that
return user?isLoggedIn

// better
return !!(user?.isLoggedIn);

Replace if/else with an optional Chaining Operator

This time we will use the chaining operator “?” , in the code below it is a little difficult to read but above all what can alert you is the duplication of code (for example the term “user” is written 3 times), to improve this piece of code we will use “?” which will allow access to the property of the object if it exists and otherwise receive undefined

// before
if(user && user.data && user.data.age) {
// processing
}

// after
if(user?.data?.age) {
// processing
}

Replace if/else with a Guard Clause

In the code example below we have too much imbrecation of if..else and the code is unreadable, so to simplify our if..else we should do some refactoring and simply use the guards close which is in the book Refactoring by Martin Fowler

// before
canRedirectToUsersList() {
if(isConnected) {
if(isLogin) {
if(isAdmin) {
redirectToUsersList();
} else {
console.error('you must be Admin');
}
} else {
console.error('you shouldbe Logged in');
} else {
console.error('you should be connected');
}
}

// after
canRedirectToUsersList() {
if(!isConnected) {
console.error('you should be connected');
return;
}
if(!isLogin) {
console.error('you shouldbe Logged in');
return;
}
if(!isAdmin) {
console.error('you must be Admin');
return;
}
redirectToUsersList();
}

Thank you all for the support ! Let’s get in touch on Medium, Linkedin !

Stackademic

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏
  • Follow us on Twitter(X), LinkedIn, and YouTube.
  • Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.

--

--