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
}
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
  • Try this if(key) { } – Vamsi Sep 18 '15 at 11:40
  • [Related](http://stackoverflow.com/questions/5559425/isnullorwhitespace-in-javascript) – James Thorpe Sep 18 '15 at 11:40
  • @Vamsi that works, unless `key` is `0` or `false`. Local Storage can include any type of value: http://www.w3.org/TR/2009/WD-webstorage-20090910/#the-storage-interface – nils Sep 18 '15 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. – Vamsi Sep 18 '15 at 11:43

5 Answers5

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

}
digitalfrost
  • 229
  • 2
  • 9
0

You may simply use:

if(key) {
   // to do here
}

Taking care of whitespace:

if(key && key.replace(/\s/g,'')) {
   //
}
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
}
user1438038
  • 5,821
  • 6
  • 60
  • 94
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.

Vivek
  • 4,786
  • 2
  • 18
  • 27
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.

Matt Morgan
  • 4,900
  • 4
  • 21
  • 30