0👍
The Example 1 is not obvious. In my opinion Example 2 is better. I would recommend to use a switch statement that can replace multiple if checks and it is created specifically for it.
<script>
var userCode = 777; // just for example
switch (userCode) {
case 555: // mean comparing 555 and userCode
console.log('Nope');
break;
case 444:
console.log('Nope again!');
break;
case 777:
console.log('Right! (from switch 1)');
break;
default:
console.log("No values have been provided that match");
}
var userCodeNewOne = 888; // just for example
switch (userCodeNewOne) {
case 800:
console.log('Nope');
break;
case 880:
console.log('Nope again!');
break;
case 887 + 1:
console.log('Right again! (from switch 2)');
break;
default:
console.log("No values have been provided that match");
}
var user = { // kind of what you have
isApproved: true,
currentUserIsEditor: true,
currentUserIsOwner: false,
}
switch (true) {
case user.isApproved:
console.log('yes approved');
case user.currentUserIsEditor:
console.log('yes editor');
case user.currentUserIsOwner:
console.log('nope is not a owner');
break;
default:
console.log("No values have been provided that match");
}
</script>
A break allows continuing processing in a function and just returning you out of a switch statement. You can wrap it in a function and feel free to use return keyword.
To make it clear I would use switch statement. To make it short I would create some Switch reducer like here. To make it ugly and short and bug-potential I would use Example 1.
Source:stackexchange.com