How andSelf() improves find()

We have seen how the jQuery methods filter() and find() differ. Now we see how to improve find() combining it to another useful method, andSelf(), that works smoothly with it.

I want to draw a box around my unsorted lists, and also around the included links. To do that, I can write this JavaScript oneliner:
$('ul').find('a').andSelf().css('border', '1px solid blue');
I select all the ULs in my document, than I find all the included A elements, and I join the two sets by calling andSelf(). Finally I call css() specifying that I want to put a thin blue line border around them.

Go to the full post

Choosing between filter and find

The .filter() and .find() jQuery methods look similar, and it could happen to mix them up. Still there is substantial difference between them, .filter() modifies the current set of elements, reducing it by applying the specified rule, while .find() operates on the children of the current set, returning a completely different set of elements.

Say that we are working on an HTML page containing a few lists, and we want to do something on some list items, the LI elements marked with a specific class, and we want to work on the links defined in any list item.

In the first case we'll use the .filter() method, since we want to refine the existing selection, for the latter .find() is the right choice, being our aim to select a new set elements among the children of the original set.

Here is a JavaScript code fragment:
var $li = $("li"); // 1

var $liK = $li.filter('.k'); // 2
console.log($liK, $liK.length);

var $a = $('a'); // 3
var $liA = $li.find('a'); // 4
var $LiA2 = $('a', $('li')); // 5
var $LiA3 = $('li a'); // 6
console.log($a, $a.length, " -", $liA, $liA.length, " -", $liA2, $liA2.length, " -", $liA3, $liA3.length);
1. Selecting all the LI elements in the current document.
2. Restricting the original set to the LI elements having class='k' as attribute.
3. All the anchor elements in the document.
4. Find the anchor elements children of LI elements.
5. Same result of (4), asking to jQuery to get all the A elements children of a LI.
6. Same of (4) and (5), and in this case probably the preferred way to the result.

Go to the full post

Selecting DOM elements

Selecting DOM elements of a given type in a document is a simple task, and we can easily do it using standard JavaScript functionality. Nevertheless, jQuery makes it even simpler.

Here is the code to get all the LI elements in the current document, both in plain JavaScript, and using jQuery:
var li = document.getElementsByTagName("li"); // 1
var $li = $("li"); // 2

console.log("li: ", li, li.length);
console.log("$li: ", $li, $li.length);
1. The getElementsByTagName() method returns a NodeList, a structure that is array-ish but does not derive from Array. It sports a property, length, that contains the number of element contained, and lets the user access each of them through the [] operator. An out of bound request is resolved to null.
2. A call to jQuery factory function returns a jQuery object that, for what we care here, is not different from a NodeList object, but it is enriched by extra-information and functionality, that could be useful in more a demanding context.

Go to the full post

When this does not work, use that

There is an issue in "this", the JavaScript keyword identifying the current object.
It works fine in an object member functions (AKA methods) but not in their inner functions. An easy way to bypass the problem requires us to create a member variable, that is often called "that" (or "self", but it is usually considered a weaker option).

Does it remember you an Abbott & Costello skit, "who's on first?", or it is just me? Anyway, an example should help clarifying the matter.

Say that we want to have an object, named calculator, keeping an internal status and providing a couple of methods, opA() and opB(), to perform some obscure calculations. The first operation is not too complicated, but opB() requires some messy stuff to be done, and we think that it would be a good idea to organize it defining an inner function that, among the other things, calls a free function.

It should be all not too complex to do, still we have to deal with the above mentioned issue.
var elaborate = (function(x) { // 1
    var cache = 0;

    return function(x) {
        cache += x;
        return cache;
    }
}());

var calculator = {
    status: 0,
    opA: function(x) { // 2
        this.status += x;
    },
    opB: function() { // 3
        var that = this; // 4
        var somethingComplicated = function() {
//            this.status += elaborate(this.status); // 5
            that.status += elaborate(that.status); // 6
        };
        
        somethingComplicated(); // 7
    }

    calculator.opA(3);
    calculator.opA(4);
    calculator.opB();
    console.log(calculator.status);
};
1. I defined elaborate() as a closure, so that it could keep its own status. See details in a previous post, static variable by closure.
2. This first method is trivial. It gets a parameter in input (assumed to be a numeric value), and adds it to the object property (status). To access the object property the keyword "this" is used. Not an issue here, for the object methods, the bind between "this" and the object itself is correctly done by JavaScript.
3. More complications here. In opB() we define a function, somethingComplicated(), that calls elaborate(), the closure defined in (1). The issue is that we can't use "this" in the body of somethingComplicated(), because "this", at that point, refers to the global scope or is undefined (if we "use strict" JavaScript, as we should).
4. "this" don't work as we would like in inner functions, but we can patch this behavior defining a local variable in the function, often called "that", that stores the value of "this" so to do as a bridge to the inner function.
5. As said above, this line doesn't work. "this" is undefined ("use strict") or points to the global scope. Hardly what you usually need.
6. This line saves the day. We use "that" to get access of the unavailable "this".
7. So we can happily call our somethingComplicated() inner method.

Go to the full post

Strictly or loosely false

Being Javascript a loosely typed language, comparing a value for its truthiness could lead to an unexpected behavior if you, well, do not expect it.

To perform a strict checking, you should use the strict comparison operator "triple equals", and you should be aware that by default the loose "double equals" operator is used.

There is a bunch of values that are loosely evaluate as false (friendly known as "falsy"):
var myUndef, // undefined
    myNull = null,
    myFalse = false,
    myEmpty = '', // empty string
    myZero = 0, // numeric zero
    myNan = parseInt('not a number'); // parsing a non numeric string returns NaN
    
if(myUndef || myNull || myFalse || myEmpty || myZero || myNan) // 1
    console.log('Unexpected');

try {
    if(myNotExisting) // 2
        console.log('Unexpected');
}
catch(e) {
    console.log(e);
}

if('false') { // 3
    console.log('Misleading');
}
1. All these values (undefined, false, empty string, zero, NaN) are loosely equals to the boolean false value, so the next line is not executed.
2. This variable was even not declared, checking it results in an exception of type ReferenceError.
3. The string 'false' is not converted to the boolean false value, and it is evaluated to true.

Go to the full post

Hello jQuery

If you are developing JavaScript's for a web application that should run in the wild, you know the pain of writing code that should run on large part of the available browsers. A common approach is delegating to a library the bore of taking care of the details, better if it has the side effect of providing a high level interface. A popular choice in this field is represented by jQuery, recently released in its 1.8 version.

Writing an Hello jQuery application is pretty easy.

Firstly, you'd better get the library on your local machine. You can fetch it following the instructions in Download jQuery.

Actually you could avoid this step and refer to a publicly available copy of it, see CDN hosted jQuery for details. Whichever strategy you follow, you should ensure your script gets access to the jQuery library. In my case, I have simply put the js file in the same directory of the html that you can see below.

My hello page pops up an alert with greetings after the HTML page is fully loaded. It is not much, but this ensures that the jQuery library is properly linked:
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello jQuery</title>
    <script src="jquery-1.8.0.js"></script> <!-- 1 -->
    <script>
        $(function(){ // 2
            alert("Hello from jQuery");
        });
    </script>
</head>
    <body>
        <h1>A JavaScript/jQuery powered page</h1>
    </body>
</html>
1. I ask to the browser to go and load the jQuery library. I have put it in the current folder, so I specify just its name. In production code, it would almost certainly be somewhere else.
2. I called a function named $ (just the single character "dollar"), passing to it an anonymous function that calls the alert() function. This is quite an implicit way of calling the jQuery ready event handler. Maybe it looks more clear if I rewrite it in this way:
jQuery(document).ready(function() {
    alert("Hello from jQuery");
});
The dollar sign is a mere synonym for the jQuery() function. And, if you dig in the jquery.js code, you'll find out that passing a function to jQuery is a shortcut for calling the document ready event handler.

Putting our call to alert() in the jQuery ready() body, we ensure that it is called only after the DOM document associated to the current HTML page is fully loaded.

Go to the full post

String and regular expressions

The JavaScript String class has a few methods that could be used with RegExp. Here is a breaf introduction to them: split(), search(), match(), and replace().

split

Regular expressions make String.split() more flexible:
"1, 2, 3".split(", "); // 1
"1 ,  2 ,3".split(/\s*,\s*/); // 2
1. This is how is commonly called split(). If we are sure on how the separator is, it works fine, and returns an array of three elements containg just the numbers. But what if we have no control on the blanks? And we could have no blanks, or many of them, around a comma? You usually won't be happy with the result.
2. This is the solution. A comma is the real separator, and any blank around it is eaten out.

search()

Passing a RegExp to search() on a specified string, we get back an integer representing the index of the first match, or minus one if there is no match:
"JavaScript".search(/script/); // 1
"JavaScript".search(/Script/); // 2
"JavaScript".search(/script/i); // 3
"Here is 1 for you, 3 for me, 42 for the others.".search(/\d+/g); // 4
1. The search is by default case sensitive, so the pattern here is not found, and the function call returns -1.
2. The match is found starting on 4.
3. We can override the default, saying that we want to perform a case-insensitive search, specifying the "i" flag after the pattern. This function call returns 4.
4. The global option makes no sense in this context, and it is silently ignored. The returned value is the position of the first match, 8.

match()

The match() behavior is quite articulate. Its output should be interpreted differently accordingly to the provided input. Seeing it in action should clarify what I mean:
var s = "Here is 1 for you, 3 for me, 42 for the others.";
s.match(/\d+/); // 1
s.match(/\d+/g); // 2
"My email address is someone@not.existing.zzz".match(/(\S*)@(\S*)/);
1. We ask to match() to return just the first subsequence matching the specified pattern, in this case a string of one or more digits. It returns a vector containing one element, "1".
2. Global matching, a vector is returned containing all the matching elements, in this case three strings, "1", "3", and "42".
3. The RegExp represents an email address, first part is the sequence of not-blank characters before the "at" symbol; second part is what is after it, till we get a blank. Notice that we asked match() to capture $1 and $2 as left and right side of the "at". In this case match() returns an array containing in first position the full matching element, and in the next positions $1, $2, ...

replace()

This function returns a copy of the original string where, if the RegExp is found, it is replaced by the second parameter passed:
"... javaScript ... javascript ... Javascript ...".replace(/javascript/gi, "JavaScript"); // 1
"I want to have 'doublequotes' in this string!".replace(/'([^']*)'/g, '"$1"'); // 2
1. Notice the two flags associated to the RegExp, specifying that we are preforming a global and case insensitive search. All the three JavaScript variation in the string are found and replaced by the string passed as second argument to the function.
2. What we are saying here is: search for each {g option} sequence starting with a single quote {'}, followed by any number {*} of any character but a single quote {[^']} and a single quote, and call $1 the subexpression in the round parenthesis. Then replace what you have found with a double quote, the $1 subexpression, and another double quote.

Go to the full post

Factory pattern for a more robust constructor

A JavaScript constructor is just a simple function. It should be called through the "new" operator so that it would provide its added value of setting "this" to refer to the newly created object, inheriting from the function prototype, and returning a reference to "this" object. But what if a client programmer mistakes the sense of our construct, and calls it as a simple function?

Let's think what happens when the constructor I defined in the previous post is called directly:
function Rectangle(a, b) {
    this.a = a;
    this.b = b;
}

// ...

var rx = Rectangle(6, 7); // !! bad mistake !!
So, I forgot to use "new", and Rectangle is treated by JavaScript as a normal function call. What happens is barely that, in the global scope, two properties named a and b are created (if not already there) and set to 6 and 7. Then "undefined" is returned and assigned to the variable rx.

Is this what I really wanted to happen? Hardly so. And even in that case, I should have used a different function to make clear that it was intentional, and not a silly mistake.

I can think to a couple of ways to improve my code: signaling the user programmer that he is doing something unexpected, or silently transform his mistake in the right thing. In the first case I would typically throw an exception, in the second one I would use the factory pattern.

Throwing an exception

This is the most clean but unforgiving solution. To implement it, we check "this" in our constructor function. If it is not associated to the instance of the function, it means that the user didn't call it properly. So we raise an exception, and the let the user programmer the burden to deal with it.
function Rectangle(a, b) {
    if(!(this instanceof Rectangle))
        throw 'Remember to use "new" to call a constructor!';
    
    this.a = a;
    this.b = b;
}

// ...

try {
    var rx = Rectangle(3, 4);
}
catch(e) {
    console.log(e);
}
As I said, this is clean code, and if you have a background in languages supporting static type, you should appreciate the predictability of what it is going on here. The caller does something wrong, he gets a rigorous "no, no" back.

Still, it doesn't looks right to me, when compared to the normal JavaScript behavior.

Factory pattern

Less clean, more forgiving. If someone calls a constructor as a simple function, we patch his code on the fly, converting it to a proper constructor call. The user programmer could now create a new Rectangle calling the constructor as was originally expected, or as a normal function:
function Rectangle(a, b) {
    if(!(this instanceof Rectangle))
        return new Rectangle();

    this.a = a;
    this.b = b;
}

// ...

var rf = Rectangle(12, 2);
// ...
Your choice

I feel that using the factory pattern is more in the JavaScript way of writing code, but I guess this is a matter of which kind of application you are developing, team programming conventions, and the such.

In any case, I would suggest you to choose one of the two approaches (or three, if you think that, after all, not checking is a viable option), and keep it in all your project.

Go to the full post

JavaScript constructor

If you have a background in strong-typed programming languages (as I have, incidentally), the JavaScript concept of class could look fuzzier than expected.

Here I show a standard way of defining a class, with a variation.

You are need in your code a lot of rectangles. In C++, Java(, etc), you would define a class Rectangle, and put in it all the relevant data and method. The JavaScript approach is different: you define a function where you create its associated data properties, using the parameter passed by the user, and let the function inherit from its prototype all the other properties you need.

This function smells like a constructor, acts like it, so it is actually called constructor, and typically given a name starting with an uppercase letter to visually show that here there is something special. But remember that, from the JavaScript point of view, it is just a plain function. The magic is done when we call it through the "new" operator. It is its job to perform the association between the constructor and its prototype, and make the constructor return by default its "this" pointer.

Here is an example where I define, instantiate, and use a Rectangle:
function Rectangle(a, b) {
    this.a = a;
    this.b = b;
}

Rectangle.prototype = {
    constructor: Rectangle, // 1
    toString: function() { return "a = " + this.a + ", b = " + this.b; }, // 2
    area: function() { return this.a * this.b; },
    perimeter: function() { return 2 * (this.a + this.b); }
}
    
var r = new Rectangle(4, 10); // 3
console.log("rectangle: ", r.toString()); // 4
console.log("area: ", r.area());
console.log("perimeter: ", r.perimeter());
console.log("Is r a rectangle? ", r instanceof Rectangle); // 5
console.log("Rectangle constructor: ", Rectangle.prototype.constructor); // 6
1. Backlink from the Rectangle prototype and its constructor.
2. All the JavaScript objects have a toString() method, here we redefine it to give some useful information to this specific type.
3. This is the core of the story: we call Rectangle through the "new" operator. If we forget to do it, we do not create a new object, we simply call a function that creates a couple of properties in the global scope and returns an undefined value.
4. Now we can use r as a Rectangle object.
5. Notice that the instanceof operator performs a check of the object against a constructor. Actually it won't check if the object has been built through that constructor, but if it inherits from the constructor's prototype.
6. If you comment out the line (1), you'll see here why we need it. Defining a function prototype as showed, leads to overwriting the default constructor property, breaking the backlink to that function. So we have to reset it.

To avoid the nuisance of (6) we could create just the properties we really need, and not redefine the complete prototype:
Rectangle.prototype.area = function() { return this.a * this.b; };
Rectangle.prototype.perimeter = function() { return 2 * (this.a + this.b); };
Rectangle.prototype.toString = function() { return "a = " + this.a + ", b = " + this.b; };
Choose whichever approach you think is more suitable to you.

The weakest point in this design is in (3). Rectangle is just a function, calling it directly is not an error, from the JavaScript perspective, even if it almost ever it doesn't make much sense and leads to a disaster.

Using the factory pattern our code would be stronger, as I am going to show in the next post.

Go to the full post

Currying and binding

If you wonder where the term currying is coming form, the answer is in the Haskell Brooks Curry logician name, and it refers to the partial application of parameters to a function. In JavaScript this is done by the bind() method, defined in ECMAScript 5.

And if you wonder what is all this fuss about binding and currying, you probably don't have a background in functional programming or, as it is my case, in C++. But don't worry, it is easy to catch up, and I reckon you are going to fall in love with them too.

Say that you have written a complicated function, you spent a lot of time to develop, test, and maintain it. You are very happy with it, and your users too. Let's simulate it with something a bit simpler:
function sum(x, y) {
    return x + y;
}
Then you find out that your cool function is often used passing always only a "real" parameter, being the other just a constant. In my example, the story would be that I wrote a sum() function, but I find out that the users often need just an increase(). Duplicating the code looks a poor solution, it would be better to create an adapter that provides just a more natural interface to the user, but keep almost all the coding effort in the original function.

Here I define next(), as a synonym of sum() that always uses 1 as a first parameter, and lets the user specify the other one:
var next = sum.bind(null, 1);

console.log("original interface", sum(42, 1));
console.log("more natural solution", next(42));
Good. But what is the null I passed to bind() as first parameter?

The fact is that JavaScript() bind() is not only about currying but, as its name suggests, it also performs an optional binding of the function to a specified object. In the previous case we didn't have any object interested in this feature, so I just passed a null instead.

To see bind() in full action, let's change a bit the startup condition. We already have an increasing function, but now it is a method, bound to an object:
var calculator = {
    step: 1,
    increase: function(x) {
        return this.step + x;
    }
};
console.log(calculator.increase(42));
calculator.step = 2; // 1
console.log("Double step: ", calculator.increase(42));
As we see in (1) it is pretty simple to change the increasing step in my calculator, but the user it is not completely happy with this solution. He didn't care of such a flexible solution, what he needs is just a function that returns its passed parameter increased by 2.

Luckily, we know that using bind() we can associate a function to different object, like this:
var step2 = calculator.increase.bind({step: 2}); 
console.log(step2(42));
We call bind() on the calculator.increase() method, and we pass to it as first (and only) parameter its new "this". In this case we don't want the step to be modifiable by the user, so we pass the object anonymously, making its reference lost to the outside world.

Go to the full post

One scope, more closures

JavaScript uses closure as an elegant way to hide a function internal status the rest of the world. It is simple to extend the concept and let more closures share the same variables.

My original sequence generator had its status defined as a property, and as such visible by everybody who had access to the function itself. I decided that was bad, and I refactored it as a closure. Cool, but the client programmer needs to modify the sequence internal status, to be able to skip ahead of a few numbers when needed.

To achieve this result, we need to do a substantial change to our code:
var sequence = (function() {
    var current = 0;
    return { // 1
        get: function() { // 2
            return current++;
        },
        skip: function(delta) { // 3
            if(delta > 0) // 4
                current += delta;
        }
    }
}());
1. The external anonymous function does not return anymore a single function, but an object containing a couple of properties, that happens to be functions.
2. The first property is named get, and it actually is our old sequence generator.
3. Here is the required improvement, a function named skip that changes the sequence generator internal status.
4. I didn't provide much error handling to the code, but I couldn't help to put at least this line, meant to avoid the user to move the sequence back and forth.

A use test for the new sequence:
for(var i = 0; i < 3; ++i)
    console.log(sequence.get()); // 1
sequence.skip(3); // 2
for(var i = 0; i < 3; ++i)
    console.log(sequence.get());
1. Get each time a new sequence number, starting from zero.
2. Skip three numbers in the sequence, before getting more numbers.

Go to the full post

Closure for static variable

Function static variable in JavaScript are easily emulated by function property. But if we want to make it private to the function, we'd better use a closure.

The first times you see a JavaScript closure at work, you could get lost in the code, but being it such a common paradigm, you are going to get used to it in almost no time:
var sequence = (function() { // 1
    var current = 0; // 2
    return function() { // 3
        return current++;
    }
}()); // 4

for(var i = 0; i < 3; ++i)
    console.log(sequence());
1. We define as a variable as ... what? There's an anonymous function definition starting here, and if we jump to (4) we see that the function is invoked just after being defined.
2. In the function body we see a local variable definition, that results being private to the function. No way anyone outside could see or modify it.
3. And here we see what our anonymous function returns: another function! This internal function does the dirty job of post-incrementing the current sequence number and returning it.
4. This means that JavaScript has to invoke the anonymous function, that returns the internal function, that returns - when called - the sequence number.

A bit contrived, isn't it? But the good news is that now we can simply call our "sequence" variable to increase and get the sequence number, exactly in the same way we called the original sequence generator. And, as required, its internal status is not visible anymore from outside.

Go to the full post

Static variable emulation

Keeping in mind that JavaScript considers functions just like specialized objects, it is easy to define something that acts like a C static variable.

As an example, let's see how we can implement and use a sequence generator:
sequence.value = 0; // 1
function sequence() {
    return sequence.value++; // 2
}

for(var i = 0; i < 3; ++i)
    console.log(sequence()); // 3
1. Define a property named value in the sequence function, initialized to zero. In this way we don't pollute the namespace in which the function is defined with a name that is used just by the function.
2. The current value is returned and then incremented.
3. Calling our function we get a new increased value each time.

This could be good enough in many case, but the fact that the internal status of the sequence function is visible and modifiable from anyone that sees the function itself could be sometimes worrisome.

A better solution, as we'll see soon, is to refactor our sequence function to become a closure.

Go to the full post

The Math object

The JavaScript developer has access to a bunch of commonplace mathematical constants and functions through the Math object. As official reference you should check the ECMA-262 5.1 standard, even if I should confess that I find more readable the Mozilla Developer page.

To calculate a circumference, it is nice to have a PI constant available:
var radius = 1;
var circ = 2 * Math.PI * radius;
console.log("Circumference is ", circ);
The resulting value should be something around 6.283185307179586.

We can convert a number to integer by approximation using round(), or we can use ceil() and floor(), to flatten the result to the left or to the right.
Let's see what happen applying these functions to the natural logarithm of 10:
var value = Math.LN10;
console.log(Math.floor(value), " <= ", value, " <= ", Math.ceil(value));
console.log("Rounding", value, " -> ", Math.round(value));
The max() and min() functions accept in input any (reasonable) number of parameters, and its returned value is the bigger or smaller one in the lot.
var values = [ -42, 5, Math.E ];
console.log(Math.max(values[0], values[1], values[2]));
console.log(Math.min(values[0], values[1], values[2]));
Min is -42, max is 5.

There are also the usual functions to calculate exponential values, Math.exp(), logarithm,

Math.log(), power, Math.pow(), a short cut for square roots, sqrt(), and the common trigonometric functions.

Playing around with JavaScript numerical functions, you can end up getting Infinity, -Infinity, and NaN.
console.log("Divide by zero:", 3 / 0); // Infinity
console.log("Divide by zero:", -3 / 0);  // -Infinity
console.log("Not a number:", 0 / 0);
console.log("Not a number:", Math.sqrt(-2)); // Nan

Go to the full post

Primitive or wrapper object?

JavaScript is a very forgiven language, we can often be very vague when considering the type of a variable. Usually we can think of primitive instances almost as if they were wrapper objects. Still there is a subtle difference, and we'd better be aware of it.

See this variable definition:
var rawStr = "test"; // 1
var objStr = new String("test"); // 2
1. A primitive string is defined.
2. A wrapper object String is defined.

The two variables could be usually considered as identical, still they are not strictly the same:
if(rawStr == objStr) // 1
    console.log("rawStr is a " + typeof(rawStr) + ", objStr is a " + typeof(objStr));
if(rawStr !== objStr) // 2
    console.log("strictly speaking, a string is not equal to an object String");
1. A raw string and a wrapper String containing the same sequence of characters are loosely seen as equal, but the typeof() operator shows that they actually have a different type (string and object).
2. If we strictly compare them, we see that they are actually different.

Same behavior applies to numbers and booleans:
var rawNum = 42;
var objNum = new Number(42);
if(rawNum == objNum)
    console.log("rawNum is a " + typeof(rawNum) + ", objNum is a " + typeof(objNum));
if(rawNum !== objNum)
    console.log("strictly speaking, a number is not equal to an object Number");

Go to the full post

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.

Go to the full post