Early return for more readability
By returning early from a method, we can reduce the nested conditions and make code more readable.
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function anyMethod (object) {
if (object) {
let token = localStorage.getItem("token");
if(token){
localStorage.setItem(`${token}_valid`, true);
return token;
}
else {
localStorage.setItem('token', "default-token")
return;
}
}
return;
}
The above can be written as
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function anyMethod (object) {
if (!object) return; // Avoiding nested condtions by returning early
let token = localStorage.getItem('token');
if(token){
localStorage.setItem(`${token}_valid`, true);
return token;
}
else {
localStorage.setItem('token', "default-token")
return;
}
}
which is more readable.