preface
For if else in our code, we can use logical judgements, or better yet, ternary judgements to optimize our code. In addition to reducing the cost of maintenance projects, it also improves code readability. Let’s start with the simplest if else example.
The simplest if… else… Or switch is the beginning of JavaScript, which we’ll briefly cover here:
if (workIsDone === true){
eatDinner();
} else {
keepCoding();
}
Copy the code
Expressions and declarative sentences
First we need to know what are Expressions and what are Statements.
An expression is any sentence used to expand the JavaScript engine and produce a value.
For example, it can be a number, array, object, regular expression, assignment, function.
Declarative sentence This is any sentence used to make something happen to the JavaScript engine, or by side effects.
Examples: conditional imperatives, variables, loops, returns, try/catch/finally.
Conditions and true and false values
What is true? What is a fake? Things change, but JavaScript engines are defined.
false
We can simply use A == false to determine false values.
'' or '' or '' 0 or -0 null undefined NaN falseCopy the code
Note that using a template string without filling it with any values will also return false.
true
The false is true
How to write conditional expressions gracefully
Remember De Morgan’s Laws?
We can use it to simplify complex conditional judgments:
! (A || B) === (! A && ! B) // true ! (A && B) === (! A || ! B) // trueCopy the code
Actual part
For Google Analytics (GA), we don’t want to upload the author’s data, as well as the test environment’s data, to interfere with the accuracy of the data. We can then ask the user if they are the author and if they are in a test environment to determine if they need to send Google Analytics data to Google servers.
Suppose two functions are already written, such as isAuthor() and isTestingEnvironment().
We only send data to Google servers if we are not the author or if the current environment is not a test environment.
const enableGA = ! (isAuthor() || isTestingEnvironment()); const betterEnableGA = ! isAuthor() && ! isTestingEnvironment();Copy the code
Of course, a better way to write this is to send data to Google servers only if the user is not the author and not in the test environment.
const enableGA = isNotAuthor() && isNotTestingEnvironment();
Copy the code
Different ways to optimize if else
Replace the simple if statement with &&
if (user && user.canDeletePost) {
deletePost();
}
Copy the code
The above code can be replaced by:
user && user.canDeletePost && deletePost();
Copy the code
Replace the if else statements to | |
We’ll use a simple function to determine the length of a user’s password as an example. If you have better snippets, feel free to leave them in the comments section at the bottom.
let strength = null;
if (password.length > 7) {
strength = 'Strong';
} else {
strength = 'Weak';
}
Copy the code
The above code can be replaced by:
const strength = (password.length > 7) && 'Strong' || 'Weak';
Copy the code
However, use && and | | can increase the combination of the layer number of programmers reading the code thinking, a more good practice is to use the ternary operator (ternary operator).
It is worth noting that if the A after your && is A falsy value, it will never return, but return B.
condition && A || B; // For example: let password = 'abcdefg1234'; (password.length > 7) && false || 'Weak'; // 'Weak' password = 'a'; (password.length > 7) && false || 'Weak'; // 'Weak'Copy the code
We can use ternary operators instead of logical operators to better express statements.
Ternary operator
The simplest ternary operator would be, is the condition true? Return A, or return B.
condition ? A : B;
Copy the code
For the above example, the code snippet to determine the length of the password could be changed to:
const strength = (password.length > 7) ? 'Strong' : 'Weak';
Copy the code
Another example is the code snippet that can be derived from an AJAX library that supports multiple browsers:
let xmlhttp = null; If (window.xmlhttprequest) {// modern browsers XMLHTTP = new XMLHttpRequest(); } else if (window.activexObject) {// Old IE version (IE <= 6) XMLHTTP = new ActiveXObject(' microsoft.xmlhttp '); }Copy the code
We can use logical operators to optimize the above code snippet:
const xmlhttp = window.XMLHttpRequest && new XMLHttpRequest()
|| window.ActiveXObject && new ActiveXObject('Microsoft.XMLHTTP')
|| null;
Copy the code
Or use better ternary operators to optimize the code snippet above:
const xmlhttp = window.XMLHttpRequest
? new XMLHttpRequest()
: window.ActiveXObject
? new ActiveXObject('Microsoft.XMLHTTP')
: null;
Copy the code
It is worth noting that the ternary judgment is joined from right to left:
// A? B : C ? D : E ? F: G // is equivalent to the following statement (A? B : (C ? D : (E ? F : G))) // BCopy the code
However, you might want to write:
(((A ? B : C) ? D : E )? F : G) // F
Copy the code
So remember to parentheses yourself to control how your code is parsed together.
Afterword.
Last week, we organized a front-end Code Review conference where we optimized if… else… Let me understand. After that, I spent some time on logical and ternary judgements. I hope to reach the stage of knowing what it is and why it is.
For the first code, we can simplify it to the following:
workIsDone ? eatDinner() : keepCoding();
Copy the code
The resources
- Conditional JavaScript for Experts – Hacker Noon
- De Morgan’s laws – Wikipedia