In order to code less and do more, one can benefit from type coercion. I will explain this with 2 examples.
Example 1
Return error, if there is no error return warning. Otherwise return empty stringSolution 1
function showMessage(errorMsg,warningMsg){
var result="";
if(errorMsg) result= errorMsg;
else result = warningMsg;
return result;
}
Solution 2 with ternary operators
function showMessage(errorMsg,warningMsg){
return errorMsg ? errorMsg : (warningMsg ? warningMessage: '')
}
Solution 3 using type coercion
function showMessage(errorMsg,warningMsg){
return errorMsg || warningMsg || '';
}
In the third solution, logical OR operator indicates that if first sentence is not true, then return second sentence.
When the example is getting complex, you can observe the advantage more easily.
Example 2
If the element is dirty and if there is an error than return error,if element is dirty and there is no error and there is a warning return the warning. Otherwise return empty string.
Solution 1
function showMessage(isDirty,errorMsg,warningMsg){
var result="";
if(isDirty){
if(errorMsg) result= errorMsg;
else result = warningMsg;
}
return result;
}
Solution 2 with ternary operators
function showMessage(isDirty,errorMsg,warningMsg){
return isDirty? (errorMsg ? errorMsg : (warningMsg ? warningMessage: '')):''
}
Solution 3 using type coercion
function showMessage(isDirty, errorMsg,warningMsg){In the third solution, logical AND operator indicates that if first or second statement is false, then return false, if both or them are true, then return the second statement.
return (isDirty && (errorMsg || warningMsg)) || '';
}
The following table shows all combinations of the logical AND and OR operators in javascript.
a= true b =true | a=true b =false | a=false b=true | a=false b=false | |
---|---|---|---|---|
a AND b | b | b | a | a |
a OR b | a | a | b | b |
Please note that, "X= false" means the following statement returns true: "X == false" The following list shows the X values that result in false
- null
- undefined
- false
- Empty String
- 0
- []
References
[1] You Don't Know JS: ES6 & Beyond Chapter 4
No comments:
Post a Comment