Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for validity

Tags:

javascript

I'd like to know the difference (if any) between the following:

if( someDOMElement.someProperty )
{
...

if( someDOMElement.someProperty != null )
{
...

if( someDOMElement.someProperty != undefined )
{
...

Is one safer than the others?

like image 656
Konrad Avatar asked Aug 25 '26 11:08

Konrad


2 Answers

Those will all do the same thing, and one isn't more error-prone than the others. Whereas if you were using !== rather than !=, the second two would only be true if the value really were null (the second one) or undefined (the third one), because the !== operator doesn't do coercion.

Javascript will coerce values during comparisons with != or ==, so for example:

alert(false == 0);   // alerts "true"
alert(false === 0);  // alerts "false"

The === and !== operators let you control that behavior. The rules for what coercions occur are detailed in the spec (and a bit complicated), but just a simple "is this thing not 0, "", null, or undefined?" can be written simply if (thingy) and it works well. 0, "", null, and undefined are all "falsey".

Sean Kinsey has a point about some host objects, though I think most if not all DOM element properties will be fine. In particular, I've seen COM objects exhibit some interesting behavior, such as if (comObject.property) evaluating true when if (comObject.property == null) also evaluates true. (In my case, it was COM objects exposed as part of the server-side API of a product I was using; I use Javascript server-side as well as client-side.) Worth being aware that that can happen. When you're dealing with Javascript objects and (in my experience) DOM objects, you're fine.

like image 68
T.J. Crowder Avatar answered Aug 27 '26 01:08

T.J. Crowder


Assuming that someDOMElement is not null, no particular differences:

http://www.steinbit.org/words/programming/comparison-in-javascript

There would be a difference if you use !==

like image 44
mamoo Avatar answered Aug 27 '26 03:08

mamoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!