Blog

  • Home /
  • Blog /
  • Learning JavaScript – Checking The Declaration of a Variable

Learning JavaScript – Checking The Declaration of a Variable

June 25, 2010

Judging from my previous post, some people might have come to the conclusion that I’m in the process of learning a wonderful programming language called JavaScript. Well, they’re right! It is a fascinating programming language although it has its quirks and pitfalls.

Have a look at the following piece of code:

The if statement tries to check for the existence of a variable called someVariable which is not declared. Because it’s not declared, the code generated the following reference error:

"someVariable is not defined"

Nonetheless, the following line of code nicely outputs the text “Hi there” which means that the previous code block still executes.

Suppose we did bother to declare someVariable but that it doesn’t contain a value that evaluates to true. In that case we’d still have the same outcome which is not what we intended. 

A better way to check for the existence of someVariable is to use typeof instead:

This still yields the same output as the previous code sample but now without the reference error. typeof always returns a string no matter what, but the difference now is that we’re testing whether the variable has a value besides undefined.

So the following piece of code outputs “Hello JS Ninja” on the screen:

On the other hand, the following piece of code again results in the message “Hi there”:

var someString = "Hi there";
if(someVariable)
    someString = "Hello JS Ninja";

This is the part where I usually get a headache and have to go search for aspirin.

Till next time.

Profile picture of Jan Van Ryswyck

Jan Van Ryswyck

Thank you for visiting my blog. I’m a professional software developer since Y2K. A blogger since Y2K+5. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Comments

About

Thank you for visiting my website. I’m a professional software developer since Y2K. A blogger since Y2K+5. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be