Coding with Jesse

JavaScript Functions are Variables

December 29th, 2007

JavaScript functions are variables, and this is a big difference between JavaScript and many other programming languages. It can be a bit of a paradigm shift for people new to JavaScript, but it allows for some really cool things you can't do in many other languages.

When I say functions are variables, I mean that they're treated much the same as arrays, numbers, strings and objects. That means you can do some neat things.

You can define and redefine functions as local variables:

var myFunc;

if (Math.random() < 0.5) {
    myFunc = function() {
        alert('heads');
    };
} else {
    myFunc = function() {
        alert('tails');
    };
}

myFunc(); // alerts "heads" or "tails" depending on random value

You can also pass functions as parameters to other functions, which is very useful for callback functions:

function do_something(callback_function) {
    alert('hello');

    if (callback_function) {
        callback_function();
    }
}

var my_callback = function() {
    alert('goodbye');
};

do_something(my_callback); // alerts "hello" and then "goodbye"

You can also return a function from a function:

function get_multiplier(factor) {
    return function(num) {
        return num * factor;
    };
}

var times_5 = get_multiplier(5);
var result = times_5(10);

alert(result); // alerts "50"

var six_times_two = get_multiplier(6)(2);

alert(six_times_two); // alerts "12"

You can also define "anonymous" functions without a name and even execute them:

(function(first_name, get_last_name) {
    var last_name = get_last_name();

    alert(first_name + ' ' + last_name); // alerts "Jesse Skinner";
})('Jesse', function(){ return 'Skinner'; });

Note that in order to execute an anonymous function you have to wrap it in () parentheses first.

So that's just some of the unusual stuff you can do with JavaScript. Once you get familiar with the concept, you can really start to reuse code in great new ways.

Hallelujah! IE8 Passes the Acid2 Test

December 20th, 2007

We thought this day would never come: Internet Explorer 8 now renders the "Acid2 Face" correctly in IE8 standards mode!

Apparently we can expect to see Internet Explorer 8 in at least Beta form in early 2008. According to the IE blog:

The key goal (for the Web Standards Project as well as many other groups and individuals) is interoperability. As a developer, I’d prefer to not have to write the same site multiple times for different browsers. Standards are a (critical!) means to this end, and we focus on the standards that will help actual, real-world interoperability the most.

Sounds like the IE team has finally seen the light! :)