If you are still a newbie, and after reading all these tips and each one is to use them later, you will write more concise and efficient JavaScript programs.
Indeed, JavaScript experts have used these techniques to write many powerful and efficient JavaScript programs. But you can do this.
Powerful && and || expressions
You may have seen them in JavaScript libraries and JavaScript frameworks, so let's start with a few basic examples:
Example 1. || (or)
Set default values, usually
function documentTitle(theTitle) {
if (!theTitle) {
theTitle = "Untitled Document";
}
}
Use this instead:
function documentTitle(theTitle) {
theTitle = theTitle || "Untitled Document";
}
Analysis:
First, read the following "tip" box to review how JavaScript determines Boolean values
|| The operator first determines the true or false expression from the left. If it is true, immediately return the value returned by the left expression; if the left expression is judged as false, continue to judge the right expression and return the value of the right expression
If theTitle is judged as false, the value of the expression on the right is returned. In other words, if theTitle variable is judged as true, the value of theTitle is returned.
! hint:
JavaScript determines that it is false: null, false, 0, undefined, NaN and "" (empty string).
Remember that the values of NaN classes like Infinity are judged to be true or not false. However, NaN is judged to be false.
Except for the above, all other values are judged to be true.
Example 2. &&(and)
Don't do this:
function isAdult(age) { if (age && age > 17) { return true; } else { return false; } }
Use this instead:
function isAdult(age) {
return age && age > 17;
}
Analysis:
The && operator determines the expression from the left. If the expression on the left is judged as false, this returns false immediately, regardless of whether the expression on the right is true.
If the expression on the left is true, continue to judge the expression on the right, and then return the result of the expression on the right
This is getting more and more interesting
Example 3.
Don't do this:
if (userName) { logIn(userName); } else { signUp(); }
Use this instead:
userName && logIn(userName) || signUp();
Analysis:
If userName is true, call the logIn function and pass the userName variable
If userName is false, call the logIn function without passing any variables
Example 4.
Don't do this:
var userID; if (userName && ) { userID = ; } else { userID = null; }
Use this instead:
var userID = userName && && ;
Analysis:
If userName is true, it is called and checked whether it is true; if it is returned, it returns the return value of the third expression
If userName is empty, return null
The above is the first JavaScript tip shared with you in this article. I hope you like it.