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.

6 thoughts on “Learning JavaScript – Checking The Declaration of a Variable

  1. I use this helper method in my js; you might find it useful?
    picked up the technique from comments of some blog post long ago

    function isUndefinedOrNull(x) {
    var u; // undefined var
    if(x === u) { // similar to [typeof x == “undefined”]
    return true;
    }
    // else
    return x === null;
    }

  2. Well, I usually use
    if (window.someVariable)
    and it works.
    The problems come when the script is not run in a browser (so no window object) and when someVariable is set, but null, NaN, empty string or 0. For making a script usable in any environment, I usually define a global variable, which would be window in a browser:
    var global = (function() { return this; })();
    This is a neat trick to get to the root object from anywhere. In order to solve the second problem, well, that is solved on a case to case basis.
    Let’s say I have a variable that is supposed to be a number. I can use this code:
    var someString=getInputFromUser();
    var numericVariable= (someString);
    if (numericVariable || numericVariable===0) …
    Also a confusing thing in Javascript is that comparing == null returns true when the value is either null or undefined. This works perfectly in some scenarios, but in others not.
    One last thing worth mentioning is the hasOwnProperty function, that works on objects (but not on the window object) like this:
    var x={};
    x.y=null;
    alert( x.hasOwnProperty(‘y’) );// true
    alert( x.hasOwnProperty(‘z’) );// false

    But check this out:
    var x={};
    x.y=undefined; //undefined is a keyword one can use AND OVERWRITE so you can’t depend on it
    alert( x.hasOwnProperty(‘y’) );// true!!
    alert( x.hasOwnProperty(‘z’) );// false

    to really remove a variable from an object you can use:
    delete x.y;
    alert( x.hasOwnProperty(‘y’) );// false
    alert( x.hasOwnProperty(‘z’) );// false

  3. I’ve sent you a rather long comment before, but it just vanished. I do hope it’s just waiting for moderation. A message could do wonders.

  4. The code works as expected. JavaScript equates undefined, null, 0 and “” (empty string) as false. It’s how the language is designed to work. I think people get into trouble with JavaScript because it “looks” like languages they’re familiar with and so they think they can “puzzle” it out. I know I made that mistake. Do yourself a favor and get a copy of Crockford’s, “JavaScript, The Good Parts”.

    Also, you can just test for undefined as follows:

    if (someVariable === undefined)

    undefined is a keyword

Comments are closed.

Find me

RSS
Facebook
Twitter
LinkedIn
SOCIALICON
SOCIALICON

Disclaimer

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