I am trying to understand how to use logical operators with my code and be as efficient as possible.
Let's say I have this variable:
var key = localStorage.getItem('keyName');
And this is my conditional:
if (key !== null && key !== '' && key !== ' ') { // localStorage key exists and is not empty or a single space
// Do something with key
}
Is there a way to write it more efficiently? I tried this, but it's not working:
if (key !== null && '' && ' ') {
// Do something with key
}
if( value ) {
}
will evaluate to true if value is not:
so key !== null && key !== ''
can be replaced by key
We can use /\\S/.test(key)
to test for a string that is just spaces (1 or more)
so how about
if (key && /\S/.test(key) ){
}
or alternatively
if (key && key.trim()){
}
You may simply use:
if(key) {
// to do here
}
Taking care of whitespace:
if(key && key.replace(/\s/g,'')) {
//
}
You can use the trim()
method to remove any leading or trailing whitespace characters from a string. There is no shorthand notation as you did in your second code example.
if (key !== null && key.trim() !== '')
// Do something with key
}
if(!~[null, '', ' '].indexOf(key))
or
if(!~[null, ''].indexOf(key.trim()))
Explanation:
indexOf return int>=0. Int >=0 means the element is found. All result will evaluate to true except 0, that's where ~
(invert/negate the result and subtract 1) comes handy.
Rest is self-explanatory, please let me know if any further explanation is required.
try:
if (key && key.trim())
the first check fails if key is null, and the second check fails if key is only whitespace. If either check fails, the whole thing fails.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.