Monday 30 April 2012

Flex: null vs undefined


This may seem like a non-post but it's actually more important than it seems at first glance.

This is when I learned that actionscript (Flex), like javascript, has both a null value (meaning null) and an undefined value meaning undefined. That totally makes sense both the languages deriving from ECMA-script. I cannot believe how long it took me to make the difference between for instance :

if (myObject == null) { /* do something */ }

and



if (myObject) { /* do something */ }

These are actually two very different things: in the first case we only catch things going wrong if the object is null and don't bother checking whether it is actually defined or not. In the second case, we know the object is both not null and defined - so we can get to work with it.

Erratum 02/11/2021 :
Reading this over several years later, I was surprised by the contents of this post.  So, I went back and checked when strict equality (===) was introduced in ECMAScipt, and realised it goes way back to the late 90s.  Also, I tried to acertain when null == undefined became true, and it certainly already was when the above post was written.  In other words, this article was flawed, and here's the fix (with my apologies).

There are basically three scenarios at play here:
- strict equality
- same value
- thruthy-ness
1.  Strict Equality
if (myObject === null) { /* do something */ }
or "strict equality" checks whether both type and value are identical.  So
2 === 2
and 
"2" !== 2
2.  Same value
if (myObject == null) { /* do something */ }
or "same value" unsurprisingly checks whether both values are the same. Thus,
2 == 2
and
"2" == 2
Taking this one step further, note that by definition:
null == undefined
(and vice versa), whereas
null !== undefined 
(strict inequality).

3. Truthyness
if (myObject) { /* do something */ }
The if predicate verifies whether the value (or value resulting from a condition) is truthy. And it so happens that both null and undefined are falsy. There is a trap of course lying herein: most people use this construct to check whether an object is defined, hence "useable" (i.e. both !null and !undefined). However, there is third case in which a value is falsy: when it is itself a boolean false. In other words the condition
if (something)
checks whether something is !null, !undefined and !false.

Thoughts?

No comments:

Online Marketing
Add blog to our blog directory blog search directory Blog Directory Blogarama - The Blog Directory