0

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
}
4
  • Try this if(key) { } Commented Sep 18, 2015 at 11:40
  • Related Commented Sep 18, 2015 at 11:40
  • @Vamsi that works, unless key is 0 or false. Local Storage can include any type of value: w3.org/TR/2009/WD-webstorage-20090910/#the-storage-interface Commented Sep 18, 2015 at 11:41
  • @nils, thanks for correcting me. I've never checked those conditions. Very helpful. :) I only assumed that the key would be some value, not the 2 options that u have mentioned. Commented Sep 18, 2015 at 11:43

5 Answers 5

1
if( value ) {
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

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()){

}
Sign up to request clarification or add additional context in comments.

1 Comment

trim() will only work from IE9 and up but this is not an issue in your case
0

You may simply use:

if(key) {
   // to do here
}

Taking care of whitespace:

if(key && key.replace(/\s/g,'')) {
   //
}

Comments

0

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
}

Comments

0

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.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.