-1

Is there any difference between the below statements:

  1. if(newValue && newValue != '') and
  2. if(newValue != '')

I have observed expression 1 in many scripts but always got confused.

Please assist!

John Dvorak
  • 26,799
  • 13
  • 69
  • 83
user1934643
  • 165
  • 1
  • 10

3 Answers3

3

if(newValue && newValue != '').

This guards against a value of null or undefined.

Out of the possible '', 0, false, undefined and null, only the last two are not equal to '' (using !=), requiring the extra condition.

console.log(null && null != '') // null -> falsy
console.log(null != '') // truthy

var undef = void 0;

console.log(undef && undef != '') // undefined -> falsy
console.log(undef != '') // truthy
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

Answer is no,

1) for (newValue && newValue != ''),it checks whether newValue exist(non false values) and its not empty

2) for if(newValue != ''),it only checks whether newValue is not empty

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

Just one more thin I thought worth adding to the answers already posted.
As you, the OP, say: you've seen the first expression in existing code many times, so you've probably seen things like this:

if (foo && foo.bar)
{
    foo.bar();
}

In this case, this is to avoid errors in certain browsers. In most modern browsers accessing somehting like localStorage.doesNotExist won't raise errors, but not all browsers support this so we: first check if the localStorage object exists, and if so, if the property can be resolved to a non-falsy value.

The same logic applies to methods of objects, that may be different in various browsers:

var domElement = document.getElementById('foobar');//might not exist, though
if (domElement && domElement.addEventListener)
{//does element exist && does it have a method called addEventListener
    domElement.addEventListener('click', functionRef, false);
}
else if (domElement && domElement.attachEvent)
{
    domElement.attachEvent('onclick', functionRef);
}

if you were to omit the first domElement in the if statement, and simply write domElement.addEventListener, that could be the same as writing null.addEventListener which throws a TypeError (because you're trying to access a property on a primitive value)

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149