Understanding when expressions are true or false

If you’ve done some C programming in the past, then you shouldn’t have any problems with understanding this concept. In JavaScript, things are really easy. Any expression which isn’t in the next list is *always* true:

  • false
  • null
  • undefined
  • empty string
  • Zero (0)
  • NaN

In practice, this means that the following snippet will always show the alert message:

var isIsTrue = "false";
if ( isIsTrue ) {
    alert(""false" is false");

Going back to the previous list, I guess it’s fair to say that we’re facing a somewhat big list. There are some things that may catch you “out of balance”. Here’s a quick example. What should happen in the next snippet:

var user = {
    nome: "Luis",
    address: "Fx"
if (user.age == null) {
    alert("no age");

You probably know that accessing a non existing property should return undefined. If you run the next snippet:

alert(null === undefined);

you’ll see that  those values aren’t really the same. However, the initial test (user.age == null ) will still work and you’ll get the alert. So, even though you’ve written incorrect code, things worked out (don’t use null for nonexistent properties and please please please don’t ever use the == operator). You might not be so lucky in other scenarios.

And that’s it. Keep tuned for more on JavaScript.


~ by Luis Abreu on September 2, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: