25 Jun
2010

Learning JavaScript – Checking The Declaration of a Variable

Category:UncategorizedTag: :

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:

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

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.

alert(someString);

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:

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

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:

var someString = "Hi there";
var someVariable = false;

if("undefined" !== typeof someVariable)
    someString = "Hello JS Ninja";

alert(someString);

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

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

alert(someString);

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

Till next time.

Find me

RSS
Facebook
Twitter
LinkedIn
SOCIALICON
SOCIALICON

Disclaimer

The opinions and content expressed here are my own and not those of my employer.