Did you say faster?

Now and then, I regularly meet someone who praises the advantages of the “reverse while” compared to the for loop. Yeah, it’s faster – we all know that. But no one seemed to know how faster, and the for loop is so much more readable – there’s always that little voice in my head “please think of those who’ll come after you” – so I’ve always preferred the for loop.

Since it’s raining outside and I can’t be bothered to do anything that would require my attention for more than three minutes (it’s the well-known “Sunday Night Syndrome”, that sometimes makes me watch Top Gear) I’ve taken advantage of the excellent jsperf.com and cobbled together the stupidest-simplest test for two loops. The results had my jaw drop. Check for yourself:

http://jsperf.com/the-loops

 

Posted in half-baked fun stuff with javascript | 1 Comment

About hoisting

One of the best (well, relatively) kept secrets of javascript is the so-called hoisting of variables. This had me confused until I learned about it, as some manifestation are quite fun (except when they generate a mysterious bug that you have to fix, in that case you might as well revise your concept of fun).

Take for example this (voluntarily) crappily written bit of code:

var someCondition = false, myName = "Barbara";
function sayMyName(){
    if(someCondition){
        var myName = "Oleoblitz";
    }
    return myName;
}
console.info(sayMyName());

What do you expect the output to be? “Barbara”, right? Since the Oleoblitz line is never executed, being inside the brackets of the if, and the condition is false – and the variable exists in the global scope with the value “Barbara”.

Nah. It outputs “undefined”.  This is due to the pleasant little trick called hoisting. Entering the function, the parser looks for all the variable definitions first thing and creates them, with a value of undefined. Well, it’s not exactly the first thing it does, as the arguments passed to the function are examined before of that, but it’s done before any single line inside the function is evaluated.

In the example above, this is what happens: the parser looks at the function, it sees that a var is defined (somewhere! It doesn’t count that the actual line will never be executed – at this stage the parser doesn’t even know if it will be executed or not), so it creates a myName variable with a value of undefined, since this is the default value that variables gets at declaration:

var myName = undefined;

Therefore, it has no reason to look further up the scope (in the globals, in that case) for a myName variable: it’s there already! It’s undefined, well yes, this is not what we meant, but the parser is behaving, really, as per design here – it’s not its fault. The “Oleoblitz” line will never be executed, the var will be returned by the function with its original value of undefined. That’s it.

So, if someone has ever told you to declare all your vars in one go at the beginning of the scope, now you know why: it will prevent hoisting “fun”. It’s true that bugs due to hoisting are relatively rare, but the code is much more readable, and debugging those is no joy, so it’s really a good practice to follow.

Spot the difference:

var someCondition = false, myName = "Barbara";
function sayMyName(){
    if(someCondition){
        myName = "Oleoblitz";
    }
    return myName;
}
console.info(sayMyName());

Having removing the “var” inside the function, now everything is hunky-dory: the variable is not redeclared, the line inside the brackets is not executed, the parser looks up the scope for the variable and founds it in the globals. The output is “Barbara”, phew, we are saved.

(Oleoblitz is, according to the legend, a lady from my hometown. Her father lost a bet and was bound to call his first kid with the first word he and his friends saw when stepping outside the osteria).

Posted in half-baked fun stuff with javascript | Leave a comment

Observable anonymous closure pattern with extjs / extcore

In these days at work I am using extcore; it’s the first time and I am not going to extoll its virtues or expose its defects here. Well, the methods related to dom traversing are really powerful, so powerful that most of the time they end up being actually bloated. The custom events are implemented by having two Observable objects broadcasting such events one to the other, so it’s nice and simple. Not as pleasant to use as YUI custom events but acres forward of jQuery’s, believe me *grin*. So, add to that that the anonymous closure pattern is all the rage (with good reason: global variables are solidly nailed in their place, the js engine doesn’t need to look through various levels of scope to finally ascertain that it’s a global, and it’s impossible to produce involuntary global variables) and voilà, for any who might need it, an Observable instantiable class with the anonymous closure pattern with extjs / extcore:

var namespace = {};
(function(ns, Ext, obs){
	var myClosure = function(){
		// this is our constructor.
	},
	privateVar = 1; // this is a private variable!

	Ext.extend(myClosure, Ext.util.Observable);

	function privateMethod(){
		console.info("I am private. I can't be called from outside");
	}

	myClosure.prototype.publicMethod = function(){
		console.info("I am public!");
	}

	myClosure.staticMethod = function(){
		console.info("I am static!");
	}

	myClosure.prototype.something = 10; // this is a public property!
	ns.Closure = myClosure;

}(namespace, Ext, Ext.util.Observable));

var a = new namespace.Closure();

Easy peasy. Actually there are a few other ways to do that, but this one is the most elegant between the ones I’ve found.

Posted in half-baked fun stuff with javascript | 2 Comments

How to pad strings in one line and no loops (if you ever need to)

This morning on the bus I had this very short padding function in mind (please don’t tell me to get a life, bus rides aren’t especially adventurous anyway):

var stringToPad = "something",

padTo = 20,

padWith = "x";

function padString(str, paddingLength, paddingChar) {

    return str + new Array(paddingLength-str.length + 1).join(paddingChar);

}

padString(stringToPad, padTo, padWith);   //somethingxxxxxxxxxx - (padded!)

Not especially useful, but an exercise in conciseness :)

Posted in half-baked fun stuff with javascript | 2 Comments

Sette e mezzo

This game is played only in one particular time and place: at your home, when you’re six and it’s Christmas. It’s a well watered-down version of blackjack, where you have to do seven and a half points, and not more.

I put together this javascript version in one night. I am nearly offended with myself at the misery of the Christmas theme in my layout, but the code itself is pretty neat, a nice example of OO javascript, that implements an MVC model. The little AI brain of your computer opponent does just a quick math on the probabilities of the next card be a favourable one – no cheating, I swear.

I am working at a new version of the game, that will get rid of the pathetic tree background – but design-wise, I am really a bit lost for inspiration here, shortly of re-creating the look of the actual game table for Sette e Mezzo: a chequered table-cloth, covered in used dishes, half-empty glasses and breadcrumbs.

Play Sette e Mezzo (opens in a new window)

Things interesting here: awkward but fully functional tentative to reproduce the YUI custom events in jQuery, and the state of the game is persisted without cookies, using window.name as a storage space. When you refresh, the game is reset but not the scores. Tested in Firefox, Chrome and IE8.

Posted in half-baked fun stuff with javascript | Leave a comment

Welcome to my “new” website!

It’s been four years since I moved to London to be a front-end engineer, and the other day I realized that my personal website was still advertising my Italian web agency. Time for a change! The change, so far, may look rather unambitious :) , but in the next few days I am going to add more content, to the point, I hope, to make this website somewhat interesting.

Posted in Uncategorized | Leave a comment