extras

Welcome!

Julian's photo Hi there! I'm Julian M Bucknall, a programmer by trade, an actor by ambition, and an algorithms guy by osmosis. I chat here about pretty much everything but those occupations. Unless you're really lucky...

Most recently this is what I've come up with:

Declare that function! But, how?

So, I read a blog post about declaring functions in JavaScript recently. It was just about technically correct as far as it went, but, ow, the way it was written hurt (missing semicolons, invalid code samples, etc). I’ll decline to link to it, thanks very much, but instead I’ll bring out its main points together with a recommendation or two (that, in fact, the original blog post did not).

There are two ways to declare a function in JavaScript, although we can spin ’em out a bit. Ready?

"use strict";

// example 1 - function expression
var doThis = function () { console.log("doThis"); };
doThis();

// example 2 - function statement
function doThat() { console.log("doThat"); };
doThat();

// example 3 - a mix?
var doTheOther = function orThisOther(again) {
    if (again) {
        console.log("orThisOther");
    }
    else {
        console.log("doTheOther");
        orThisOther(true);
    }
};
doTheOther(false);

// example 4 - IIFE
(function () { console.log("anonymous"); })();

(If you run this code in your browser’s console, you’ll get …

doThis
doThat
doTheOther
orThisOther
anonymous

… of course.)

Whitby wave action warningIn essence, we have a variable being set to a function expression in the first example, and we have a function statement in the second example. The other two examples I’ll get to in a moment. The first example, then, reinforces the fact that functions are objects. You can create them, pass them around, save them in variables (or in properties – in which case, we call them methods – or in arrays or whatever), use them in callbacks, and invoke them. For me, this is by far one of the most important features of JavaScript, the fact that it is a functional language. Functions are objects; remember that.

The second example gives you one added benefit: function statements are “hoisted” to the start of the scope. You don’t have to declare the function before using it, in other words. The JavaScript compiler will, in essence, invisibly move the function statement to the top of the scope so that you can call it whenever you want in the scope. Yes, you got it: you can be lazy and call a function in your code before you’ve actually coded it. This is, to be honest, a pretty shady way of coding in my view. I do not recommend it at all; it makes reading and understanding the code just that little bit harder. Anyway, apart from that little trick, a function statement acts just like a function expression that’s saved in a variable, except that you are hiding the functions are objects concept. And yes, you can assign a function statement to a variable, and invoke it through that variable:

var foobar = doThat;
foobar(); // prints "doThat"

The fun starts when you mix the two, as in the third example. Actually this shows a named function expression, not a function statement being immediately assigned to a variable. The name of the function expression can be used inside the function itself to allow for recursion. The name of the function expression is not visible outside the function expression; I can’t for example just call doThisOther() in my main code: I’ll get the error “undefined”. So, example 3 is a use-case, but very limited. I can’t say I’ve ever used it in “real code”, apart from in examples like this one.

And then finally in example 4, we have an IIFE, an Immediately-Invoked Function Expression. As its name says, it’s a function expression that is called immediately. It is not saved anywhere, for example in some variable. If it weren’t immediately invoked it would be lost, there would be no reference to it anywhere. IIFEs are used all over the place in JavaScript code, it is an extremely common pattern. (Note the extra parentheses around the function expression: that’s so the JavaScript compiler determines that you are not declaring a function statement when it parses function.)

As for callbacks where commonly you provide an anonymous function expression to the function that will do the callback, all that’s happening is that the anonymous function is assigned to a parameter (that is, a variable):

var callSomeFunction = function (f) {
    console.log("Calling f...");
    f();
};

callSomeFunction(function () {
    console.log("a callback function");
});

And this produces:

Calling f...
a callback function

So, all in all, my advice is to stick to function expressions exclusively. The one single feature a function statement has that an expression does not, hoisting, can lead to less readable code, and we wouldn’t want that.

Album cover for DJ-KicksNow playing:
Thievery Corporation - Coming from the Top
(from DJ-Kicks)

 

Globals, IIFEs, this, and strict mode

It started like this: I was reading some JavaScript code, written – he says charitably – some years ago. Much simplified, it looked something like this, with all identifiers renamed to protect the guilty:

timer = {};

timer.timerID = null;

timer.cancel = function () {
    if (timer.timerID !== null) {
        clearTimeout(timer.timerID);
        timer.timerID = null;
    }
};

timer.start = function (delay, onDone) {
    timer.cancel();
    timer.timerID = setTimeout(onDone, delay);
};

Colored lightLet’s just analyze this for a moment. Yes, it’s creating a global object and then adding a bunch of methods and properties to that object. At one level then, it’s good: it minimizes the impact on the global namespace since there’s just that one global variable. And, er, that’s it. The biggest thing for me on reading this for the first time is the complete lack of closures and local variables. From that insight come two major issues: first, there is no data hiding at all. Second, this is a singleton, or, if you like in C# terms, it’s a class that acts as an already-instantiated object. In other words, there is no chance of having two timer objects. Let’s address these two points separately.

Regarding the first point, to me this code is calling out for an IIFE, an Immediately-Invoked Function Expression. This is a piece of code that is structured as a function (actually a function expression), one that is invoked as soon as it’s encountered.

(function () {
    var timerID = null,

    cancel = function () {
        if (timerID !== null) {
            clearTimeout(timerID);
            timerID = null;
        }
    },

    start = function (delay, onDone) {
        cancel();
        timerID = setTimeout(onDone, delay);
    };

    timer = {
        start: start,
        cancel: cancel
    };

})();

(Notice that the function expression is anonymous and that it is enclosed in parentheses. The reason for this latter restriction is to avoid the case that the interpreter confuses this IIFE for a function declaration.)

Anyway, in doing this, I have automatically created a closure and therefore already have some hidden local variables. I then restructured the code to take advantage of these ‘private’ variables and make the whole thing cleaner and clearer. Except there’s a subtle bit of code “misdirection” in there that, the first time I coded it, I didn’t have and the code didn’t work. What is it? Well, notice I’m declaring all the local variables of the IIFE as a single, continued var expression, with variables separated by commas? In my original code, I didn’t terminate this expression after the start function and then thereby made timer also a local variable. The only difference between the “bad” code and the “good” code is replacing a comma with a semicolon. Not exactly really obvious what’s going on, eh?

Better might to be more explicit:

    window.timer = {
        start: start,
        cancel: cancel
    };

And then I remembered a trick I’d learned a long time ago. Not a lot of people know that the this keyword for an IIFE actually refers to the global object, or window – the interpreter assumes that such anonymous functions are called as if they were methods on the global object. So we don’t in fact have to refer to window in our code. This is handy in those cases where we’re writing JavaScript code for, say, node.js, where the global object is not called window.

    this.timer = {
        start: start,
        cancel: cancel
    };

This all worked until I got conscientious and added "use strict"; at the top of the file to turn on strict mode. Boom, the code stopped working again: “this is undefined”. Eh, what?

It turns out that my old “trick” was one of those things I should have immediately ignored and forgotten (as will you right now!). This “if a function is called outside of an object context, set this to the global object” was never part of the JavaScript standard, and the newer strict rules expressly state that this is not so. In these cases, this is expressly set to null. Back to window then, or perhaps something like this where we pass in the global object explicitly:

"use strict";
(function (globalObj) {
    var timerID = null,

    cancel = function () {
        if (timerID !== null) {
            clearTimeout(timerID);
            timerID = null;
        }
    },

    start = function (delay, onDone) {
        cancel();
        timerID = setTimeout(onDone, delay);
    };

    globalObj.timer = {
        start: start,
        cancel: cancel
    };

})(window);

However, at this juncture, it starts to really make sense to take account of my second point above: why have this as a global object in the first place? Why not just make it a function that creates a new timer object: the code is almost all there anyway? (And, no, I don’t mean a constructor.)

"use strict";
var createTimer = function () {
    var timerID = null,

    cancel = function () {
        if (timerID !== null) {
            clearTimeout(timerID);
            timerID = null;
        }
    },

    start = function (delay, onDone) {
        cancel();
        timerID = setTimeout(onDone, delay);
    };

    return {
        start: start,
        cancel: cancel
    };
};

Yes, this creates a global function, so we’re almost back to square one. Just add it as a method to a global object you have already created, say a utilities object.

In fact, you could go even further: why reuse a timer object? Just set it going and when it’s done throw it away. Need a timer again? Just create another timer. Oh, and while we’re at it, let’s have an onCancel callback, and use a configuration object and pass it to the onDone and onCancel callbacks. But that’s a story for another day.

Album cover for Zen PauseNow playing:
David, Thierry - Releasing The Past
(from Zen Pause)


Best supporting actor in a comedy?

Holy crap.

Every now and then (and it’s very rare these days because of the business travel I have to do), I manage to get a role in a local theatre production. Yes, indeed, I’ve been known to act a little. In December, after some four years away from the stage apart from a very small role in The Wild Duck for Theatreworks in March 2013, I landed the role of Reverend Shandy in The Lying Kind, also for Theatreworks. The part was a hoot, as was the play, a strong British farce. We had some good houses and the audience enjoyed it immensely, as did we, the cast. Sixteen performances and I had a ball.

The Lying Kind: Reverend Shandy tries to scare off the police with a cross

Anyway, Bill Wheeler attends as many theatre productions along the Front Range in Colorado as he possibly can, and then writes some excellent reviews on his blog, Theater Colorado. He came to The Lying Kind and enjoyed it, and I certainly appreciated his review. The local paper, The Gazette, didn’t even bother, so phooey to them.

Well, it seems he does a “Best of the Year” summary as the year flips over, and this New Year was no exception. This time he divided not only the plays he’d reviewed into Drama, Comedy, and Musicals, but also into Large Companies and Small Companies, to give a broader and possibly better result (and in fact splitting the Drama section further with Micro Companies as well). The Lying Kind came in as an Honorable Mention under Comedy, Large Companies: Best Play, which is excellent news, in and of itself. But then I scanned further and…

COMEDY, LARGE COMPANIES:  BEST SUPPORTING ACTOR

Julian Bucknall as Reverend Shandy, The Lying Kind, Theatreworks.

When the Vicar comes for a visit, things get crazy.  Bucknall is fetching in fish net stockings, and the laughs are nonstop.  For a proper man of the cloth, he has a LOT of explaining to do.  Thanks, Julian.  I’ll never look at a Vicar the same again, but I'll surely be smiling about wondering what else he's wearing.

Holy crap. Best Supporting Actor? I gotta lie down.

Album cover for SkyscrapingNow playing:
ABC - Only the best will do
(from Skyscraping)


Back in the day: a PC Card adapter for USB 2.0

Time for a quick giggle as I look at some old hardware I used to use, some 14 years ago, before I take it off to recycling. This past weekend, in a box at the back of the cupboard, I found this:

PC Card adapter for 2 USB 2.0 ports - top

It’s an adapter for a laptop that didn’t have USB 2.0 ports but that did have a PC Card slot.

PC Card adapter for 2 USB 2.0 ports - end

Way back when, that’s exactly what I had: a big chunky laptop with USB 1.1 ports but no USB 2.0 ports. The laptop was recycled ages ago, but the card adapter lived on until now.

I also found a couple of Microsoft Wireless Adapters that used the same physical interface, because, yes, back then my laptop had a wired network adapter, but not a wireless one (nowadays, it’s the exact opposite in these new ultra-slim laptops):

PC Card wireless adapter

Scary stuff…

Album cover for Ancient and ModernNow playing:
Dudley, Anne - Tallis' Canon
(from Ancient and Modern)


Another chapter from the “Don’t be clever” coding style

A short and quick example of some baffling coding today. It so happens this past weekend I was updating some HTML and CSS and JavaScript on this site. One of the JavaScript source files (luckily not written by me) had this: function $$(id) { if (id.substring(1, 0) != "#" ) id = "#" + id; return $(id)[0]; } So, in other words, it takes an element id, makes sure it starts with a ‘#’, calls jQuery to return the elements with that id (of which there should be one only...

Read more »

Installing Yosemite like a pro

Way back when, I bought a black MacBook and an iPod Touch. I was – har, har – going to learn how to write Objective-C and earn millions selling apps. You know the kind of thing: Learn Objective-C … PROFIT!!!! Except Objective-C is a right royal pain in the neck – and this is coming from someone who loves JavaScript. Anyway, after a year or so, I had a better plan: use a Mac as my main laptop and get used to the Mac way. I bought a unibody 13-inch MacBook Pro, mid-2010 version...

Read more »

The Talented Mr Steve

So this happened… The phone rings. The caller id says “STS” from 949-203-0674. I know who it is; I track scam phone numbers: it’s a hobby when you work from home. I answer. “Hi, this is Julian.” Clicks, buzzes, then: “Hello, this is Steve from [somefakename]’s Tech Support Department.” “Oh, yes?” “We’ve noticed that something is wrong with your computer. My error report says it is no longer updating.” “Interesting...

Read more »

Cloud, cloud, everywhere

So I got an iPhone 6 the other day. Bully for me, I can hear you say, but this isn’t about that. It’s about the fact that Apple, in preparation for iOS 8, changed the limits and functionality on their cloud storage offering, iCloud. With all the iOS devices in the house, a while back I had to pay for extra storage to enable backups for them all. That storage was just upgraded at no extra cost to 20GB. Time, I thought to myself, to check on all the cloud storage subscriptions I actually...

Read more »

Saying goodbye to Eurydice

A couple of weeks ago, just before we disappeared off on vacation, Eury crashed. Before you start imagining car wrecks and the like, let me explain that Eury was our oldest cat. He was 18 years and 4 months old, which, for a cat, is way up there in terms of age. And by crashed I mean that, finally, all of his ailments – and let me tell you this cat had them all, pretty much – caught up with him and there was nothing more we could do. Eury was one of the original two kittens we bought...

Read more »

Restoring old negatives: the bad and the not quite so bad.

As hinted a couple of blog posts ago ( From ‘57 to 57 ), I’ve been resurrecting a stash of old film negatives from those halcyon days when I first started learning about photography after I’d bought an SLR. And by “resurrecting” I mean separating them from the stuck-together block some of them had become. A couple of people have asked me what I did, so a quick post is in order. In essence, the film processing service I used back in the day (30-35 years ago, note) put...

Read more »

Extras

Search

About Me

I'm Julian M Bucknall, an ex-pat Brit living in Colorado, an atheist, a microbrew enthusiast, a Volvo 1800S owner, a Pet Shop Boys fanboy, a slide rule and HP calculator collector, an amateur photographer, a Altoids muncher.

DevExpress

I'm Chief Technology Officer at Developer Express, a software company that writes some great controls and tools for .NET and Delphi. I'm responsible for the technology oversight and vision of the company.

Validation

Validate markup as HTML5 (beta)     Validate CSS

Bottom swirl