Is there any difference between the below statements:
if(newValue && newValue != '')
andif(newValue != '')
I have observed expression 1 in many scripts but always got confused.
Please assist!
Is there any difference between the below statements:
if(newValue && newValue != '')
andif(newValue != '')
I have observed expression 1 in many scripts but always got confused.
Please assist!
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
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
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)