Hello JavaScript, and null vs. undefined

The cool thing about JavaScript, is that you don't need almost anything to start working with it. If you reading this on a modern browser, you should have already all at hand. Maybe, if you are on Firefox, you would prefer to do download a plugin (and I'm thinking to Firebug) to have some debugging fire power. And that's it. You are ready to write your first JavaScript application.

My Hello World JavaScript application amazingly does some little more than greeting the user. It also shows what is the difference among null and undefined in this language.

If you have any reason not to use the console object, that lets you to write log without pestering the browser with a popup, you could fallback to the old, and annoying, alert() function.

Here is the HTML that I have written:
<html>
<head>
    <title>Hello JavaScript</title>
    <script type="text/javascript"></script>  <!-- script language specification -->
</head>
<body>
    <script>
        var a; // 1
        var b = null; // 2
        
        if(a == b) // 3
            console.log("undefined is loosely equal to null");
        if(a === b) // 4
            ;
        else
            console.log("undefined is strictly not equal to null");        
        
        document.write("Hello World!"); // 5
    </script>
</body>
</html>
If you are new to JavaScript there are a few interesting things to notice.

In the head section I specified the scripting language I am about to use. JavaScript is understood by a large share of browsers, and often it is assumed by default. But it is always a good idea to document that we are actually using it. Here I am writing HTML code, so the associated comment on the right is a HTML comment (less than, exclamation mark, minus minus ... minus minus, greater than).

In the body I specify a script section and in it I do a few things. Notice that here I am actually writing JavaScript code, so I follow its conventions. Among the other things, we can see that comments are in Java style, a double slash till the end of the line. I could have used also the C/C++ old-style comments (slash, star .... star, slash).
1. A variable is declared but not defined.
2. Another variable is declared, but here it is also defined, even if the associated value is just a null.
3. Undefined is similar to null, and the standard comparison operator is sort of fooled to see them as equals, so the next line is actually executed. We can see the output in the Console tab of Firebug.
4. But undefined is not the same of null, and the strict comparison operator is smart enough to detect the difference, so the next (empty) block is not executed, but we jump directly to the "else" block, and we write that log to the console.
5. In any case we politely say hello to the user.

No comments:

Post a Comment