Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

History for Ajax pages

If you write dynamic JavaScript web pages you know about the nuisance of not having the browser managing back and forward buttons for your code. There is a number of solutions to overcome this issue, in my team we tested a few of them, than we shortlisted the candidates to history.js and backbone.js, and I think we are about to use the latter.

If you need some background on the matter, you could have a look at these pages:
Mark Pilgrim put on the web some material from his book on HTML5, here is a chapter on the history API
On Google Developers, a getting started document on Ajax crawling
On the Mozilla Developer Network, an article on Manipulating the browser history
A description of the solution provided by history.js is available on github.
Also on github you can get information on backbone.js.

The point is that we can't just rely on the HTML5 solution, the so called History API (or pushState), because we should support also clients that are using older browser. Before pushState, a few indipendent solutions were designed to tweak the fragment identifier support offered by HTML4, see this page on w3.org for details, to achieve the same result. What history.js, backbone.js, and others do is providing a way to keep the code specific to each platform localized in a place.

I am going to create a simple tiny web page with history support provided by backbone.js, and to do that I need to have at hand a couple of libraries, actually, three of them: jQuery, underscore.js, and backbone itself.

The changes to my pages are driven by three links, each of them generating an event, which should result on setting some text in a div. Admittedly, nothing fancy. But bear with me.

The HTML would be something like this:
<div id="msg">Hello backbone</div>
<hr />
<p><a href="#event/id/3">Event id 3</a></p>
<p><a href="#event/id/5">Event id 5</a></p>
<p><a href="#event/id/7">Event id 7</a></p>
The interesting part is the JavaScript code, just a couple of (dense) lines:
new (Backbone.Router.extend({ // 1
  routes: { "event/id/:id": "processEvent" }, // 2
  processEvent: function(id) { $('#msg').text('Event id ' + id); } // 3
}));

Backbone.history.start(); // 4
1. An object is created here. It is an Backbone.Router extended by the object passed, that contains two properties.
2. This routes property is used to route the event generated by the user JavaScript to what it should do. Going to the backbone router we could delegate to it the job of taking care of the history. What we say to backbone here is to get each link in the format "event/id/" plus a parameter and call a function with the name specified as value (here I've chosen the name "processEvent").
3. The name of the second property should match with the value in the object defined above (I mean, "processEvent"), and its value is the function that I want to be executed by the backbone router on my request. Here I get the div with id msg, and I set its text to a different string accordingly to the passed parameter.
4. I'm ready, so I ask backbone to start the history.

Now what happens is that clicking on the link the user changes the page content and its URL in the address bar. The browser history will work fine, and we can copy the page URL, and open it in a different browser to get the expected behavior.

Go to the full post

Module pattern template

My current project makes use of different technologies, for presentation we rely on a mix of Java EE and JavaScript. We try not to mess around too much with the latter, and we strive to keep that code as readable as possible. For this reason we break the JavaScript code in modules that, ideally, are all written following the same template, so that it is easy for anyone in the team to put his hands on any piece of code available.

Here is an example of how we typically write a module.

As you will see, we use the well known module pattern, with a few specific variations:
var APP = APP || {}; // 1

APP.Module = (function(app, global, $) { // 2
  "use strict"; // 3

  var FIRM_NAME = 'XYZ'; // 4

  function Factory(options) { // 5
    var that = this; // 6

    if(!(this instanceof Factory)) { // 7
      return new Factory();
    }

    this.options = $.extend({ name: null }, options); // 8

    function _checkName() { // 9
      if(that.options.name) {
        console.log('In a private function, use that instead of this');
        return true;
      }
      else {
        return false;
      }
    }

    this.getName = function getName() { // 10
      return FIRM_NAME + (_checkName() ? ': ' + this.options.name : '');
    }

    return this; // 11
  }

  Factory.aFunction = function() { // 12
    if(this == Factory) {
      console.log('A static function has no access to instance variables');
    }
    else { // called by sayHello, see below
      console.log('Instance', this.options.name);
    }
  }

  Factory.prototype.sayHello = Factory.aFunction; // 13

  return Factory; // 14
}(APP, this, jQuery)); // 15
1. First thing, I define a namespace for all the modules. Or better, if APP is already defined, I use it as it is in the following code. Only if no APP is already available a create it from scratch.
2. In APP, I create a module named Module (usually it is a good idea choosing a better name). As you see, it is nothing more that an immediate function that receives in input three parameters, see the module last line (point 15.) to find out what they are.
3. The JavaScript code used is "strict".
4. This is a private variable (ideally, a constant) available to all the Module instances.
5. The Module's constructor. It accepts in input a variable used to set the internal object properties. In this case "options" contains just a single value, so it is an overkill not to use it. But usually options contains a large number of properties.
6. The infamous "this is that" pattern. Follow the link for more details.
7. Another well known JavaScript pattern. The constructor could be called improperly, with this check we avoid any unpleasant surprise.
8. We use jQuery, so to extends the "options" object passed to the constructor we use the jQuery .extend() function. Same functionality is provided by other frameworks, and it could also implemented with no special trouble by hands. The idea is that we want to ensure that our local "options" contains at least a property named "name". If the passed "options" has it, we will keep it, otherwise a new, empty one (or better, null), is created.
9. A private function. No one could access it outside its scope. Notice that inside it we have to use "that" to access the constructor "this".
10. A public function. It could be called from outside, and it has full access to the constructor and module properties.
11. As almost any constructor, at the end of its job it returns "this".
12. Sometimes it is useful to have a "static" (in the C++/Java sense) method in a module. Here is how we can emulate it. We can even use a trick (see 13.) to adapt this method so that it could also be called as a non-static function.
13. Here is the trick. We create a property in the Factory prototype, and we assign to it the static function. Neat.
14. Finally, the immediate function calls the constructor, so that the object is created.
15. We call the immediate function passing to it APP (the module's namespace), the current "this" (at this point it should be the global one), and jQuery (since we use it - you could pass your preferred framework instead, obviously. Or you could even pass many ones).

Here is a test usage for the above defined module:
var m1 = new APP.Module({name: 'John Smith'}); // 1
console.log(m1.getName());

var m2 = new APP.Module(); // 2
console.log(m2.getName());

APP.Module.aFunction(); // 3
console.log("Can't call a private function from outside:", m1._checkName === undefined);
console.log("Can't call an instance function from static context:", APP.Module.sayHello === undefined);
console.log("Can't call a static function from an object:", m1.aFunction === undefined);
m1.sayHello(); // 4
1. An object m1 is created, passing a name to the module.
2. Here we create an "anonymous" module, no name it is passed.
3. The static function is called on the module itself, it doesn't requires an actual instance.
4. But through that clever trick showed above on (13.) we can call the static function through an alias.

Go to the full post

Reading a JSON and looping on it

I have a JSON array of strings stored in a file, I want to read it from a JavaScript and use in someway its values. To simplify the file access, I am about to use the jQuery getJSON() function.

The JSON file, named numbers.json, contains something like this:
["Zero", "One", "Two", "Three"]

This JavaScript fragment gets asynchronously the file, and then dumps to the console any elements in the fetched JSON:
$.getJSON('numbers.json').done(function(numbers) {
  for(var i=0; i < numbers.length; ++i) {
    console.log(numbers[i]);
  }
});
Calling getJSON() we ask jQuery to fetch the content of the passed filename and, when done, calling the anonymous function passed as parameter to done(), putting in its input parameter, that I named numbers, the contained JSON. In the body of that anonymous function we have to deal with the fetched data. What I do there is simply looping on the array, and logging to the console each component.

Go to the full post

From Java objects to Json

I am pretty busy in these days. Just a few lines to remember to myself that I have a couple of blogs to think about, and it would be good write something on them once in a while.

Currently I am working on a servlet that also generates a few Json responses on request. It happens. Json is much popular in JavaScript environment (and not only there), and one should be prepared to convert data to and from that format.

That servlet I am working on, currently does this job "by hand" (yuck!) polluting the code with obscure short strings that makes a nightmare maintaining it.

A few better solutions exist. I had a fast look around and I picked up the google-gson library, that looks to me simple and powerful enough for my current requirements.

As you could guess from its name, google-gson is a project hosted by Google Code. You would find there its home page. There you could also get the latest version (currently 2.2.2) and enough documentation to start working with it.

I have written a few test cases, just to check it before start using it in the real code, but nothing worth to be written here. Have a look instead to their user guide, that includes a few examples that should be enough to let you see how it works.

Go to the full post

Three solutions to the loop problem

The lack of a block scope in JavaScript leads to what is often called The Infamous Loop Problem, where we try to use the (supposed) cycle variable in a for loop to set a callback function.

Conceptually, the solution is quite easy. The trouble is caused by the loop variable, that actually does not have a local scope, so we provide to it a local scope. In JavaScript we have only function scope, so a function would help us to find a way out.

The question is, which function? Whichever it is better for you in your context, I'd say. Let's see the three answers that I guess are more natural.

In the previous post I have written a buggy piece of code that was storing a few functions when looping on an array, an then, in another for loop, it called those functions. Now I modify it to let it work as I expected, following three different approaches.

Closure in loop

This is the most idiomatic solution using "pure" JavaScript. We wrap the code in the for loop around a closure, designed just to provide a local scope for the loop variable.
function doSomething(msg) {
    console.log(msg);
}

var messages = [ "hello", 42, { pi: 3.14 } ];
var buffer = [];

for(var i = 0; i < messages.length; ++i) {
    buffer[i] = (function(j) { // 1
        return function() { // 2
            doSomething(messages[j]);
        }
    })(i); // 3
}

// ...

for(var k = 0; k < buffer.length; ++k) {
    buffer[k]();
}
1. We put in buffer the function returned by a closure, here defined, that take as input a parameter, named j, that is assigned a value defined in (3).
2. The function returned by the closure is almost the same function we defined in the original code. The difference is that I don't use anymore the loop variable, but the closure parameter.
3. This is the core of the solution. I assigned to the closure parameter the loop variable, in this way the closure captures its current value, that now has a local scope, as required.

After a while, I guess this would look as the most natural approach, but if your JavaScript mileage is low, you could be find it a bit overwhelming. In this case, maybe you could be more at ease with the following variation.

Closure in the function

The idea is to move the closure from the for loop to the recipient function. I refactor the code above, rewriting the for loop and doSomething(), renamed doSomethingElse() for the sake of clarity.
function doSomethingElse(index) {
    return function() { // 1
        console.log(messages[index]);
    }
}

// ...

for(var i = 0; i < messages.length; ++i) {
    buffer[i] = doSomethingElse(i); // 2
}

// ...
1. The closure has been moved here. Notice that this function does not run any code, but returns a function.
2. Just a simple assignment!

This code is so much readable, but I am losing the connection between the loop (2) and the reason why I need a closure in (1). Someone who reads just doSomethingElse() would probably wonder why it returns a closure instead of doing directly its job.

jQuery.each()

If we use the jQuery library, we can get the advantages of both the previous solutions using the each() method.

We use the original doSomething() function, and we don't need a closure in the for loop, jQuery.each() is a function, so it provides its own scope.
$.each(messages, function(index, value) { // 1
    buffer[index] = function() { // 2
        doSomething(value);
    }
});
1. For each element in the messages array, we call a function where the first parameter is the current index, and value the message element currently accessed.
2. There's no need of a closure, we simply assign to the buffer element a function that calls doSomething(). The capturing of local values is performed by jQuery.each().

Go to the full post

The JavaScript infamous loop problem

There is no block scope in JavaScript. Once you get used to this truth, the loop issue stops to be mystery, and you can say goodbye to a bunch of quirky behaviors in your code.

The for loop is a typical construct where many programmers get surprised by JavaScript. So I decided to write this post to make the issue as clear as I can. In the next post I present a few alternative solutions.

Simple loop through an array

Let's start looking at a plain for loop that won't give any trouble at all. I have an array of mixed objects, I want to call for each of them a function that does something not relevant here:
function doSomething(msg) { // 1
    console.log(msg);
}

var messages = [ "hello", 42, { pi: 3.14 } ]; // 2

for(var i = 0; i < messages.length; ++i) { // 3
    doSomething(messages[i]); // 4
}
1. I don't care much of what this function actually does, logging the parameter is more than enough.
2. This is the array I want to loop through.
3. A local variable, i, is declared and used as temporary location for the current element in the array.
4. The function is called for each element in the array.

As I said, this way to walking through an array works fine. Still, we should be aware of the fact that the supposed loop variable is not actually limited to that scope, but it is available all over the function scope in which the for loop is placed.

This doesn't work

Let's think to something a bit more complicated. Say that I don't want to call immediately the other function, I want to create an array of function, so that I can call them later, after I do some other task.

I could (wrongly) think to refactor the previous piece of code in this way:
function doSomething(msg) {
    console.log(msg);
}

var messages = [ "hello", 42, { pi: 3.14 } ];
var buffer = []; // 1

for(var i = 0; i < messages.length; ++i) {
    buffer[i] = function() { // 2
        doSomething(messages[i]);
    }
}

// ...

for(var j = 0; j < buffer.length; ++j) {
    buffer[j](); // 3
}
1. Temporary place where storing the functions to be called in a second time.
2. For each element in the message array, I create an unnamed function that calls doSomething().
3. And after a while I call all the functions stored in the buffer.

At a first sight, it looks like we should have the same result of the first example. But here we get just a desolating list of "undefined".

What happened here? The problem is that the loop variable is not actually such. So, when in (3) we call doSomething() through the buffer, the index is the current value (actually, the length of the message array) and not its value when in (2) we assigned the function to the buffer.

What we need to do is to capture the current value of the loop variable in (2) so that would be used in (3). We can achieve this result in a couple of different ways, as we'll see soon.

Go to the full post

Adding a DOM element

If you have to modify an existing DOM document in the fly by adding a HTML fragment, you can use the jQuery appendTo() method, that would simplify your job. Being jQuery smart enough to create a jQuery object from a HTML literal fragment, we can even operate on it before appending it.

To add a bottom line to an HTML page, I could write:
var fragment = $('<p><i>Bottom line</i></p>'); // 1
fragment.find('i').attr('class', 'z'); // 2
fragment.appendTo('body'); // 3
1. I create a P element containing an I element, containing some text.
2. Before actually adding it to my document, I can modify it. Here I get the I element and add to it an attribute, class='z'.
3. Finally, I add my fragment at the end of the BODY element.

There is no need of writing this code on three lines, I can squeeze it on just one, but I have to be careful:
$('<p><i>Bottom line</i></p>').find('i').attr('class', 'k').end().appendTo('body');
I need to call end() before appendTo(), otherwise I put to the document only the element returned by find(), and the paragraph would be lost.

Go to the full post

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