2-player board game app This question is about the best way to declare functions in Javascript. The app is a small 2 player board game I'm working on as part of a bigger web page. Basically I have a socket which receives and send messages and the game acts according to the content of the message.

$(function () {
    var board = document.getElementById('board');
    //When a msg is received
    //structure of msg : msg = ['action','args']
    if (msg[0] === 'action1') {
        func1(args);
    } else if (msg[0] === 'action2') {
        func2(args);
    }
}

function func1(args) {
    var a, b...;
    doAction1(); //uses the DOM element board, the args and local variables
}

function func2(args) {
    var a, b...;
    doAction2();
}


Now, I was thinking of using an object the way I would do in Java but it seems that it is not the best practice. Should I use a single function like so?

$(function () {

    var game = function () {
        var gamevar1, gamevar2, ...;
        action1: function (arg) {
            doAction1();
        }

        action2: function (arg) {
            doAction2();
        }
    }

    //when a msg is received [action,param]
    game.msg[0](msg[1]);
}
Since this is all the code you posted, I'm going to assume you're only using these functions in the place they're defined, so the later code would be best. It's more readable and doesn't include unnecessary identifiers.

Your question is really about anonymous functions, not closures. To answer this question, you should ask yourself, "do I plan on using these functions elsewhere"? Since anonymous functions, by definition, are not bound to an identifier, they will be inaccessible everywhere except where they are defined.

This is the version that I would recommend:

$(function () {

    var game = function () {
        var gamevar1, gamevar2, ...;
        action1: function (arg) {
            doAction1();
        }

        action2: function (arg) {
            doAction2();
        }
    }

    //when a msg is received [action,param]
    game.msg[0](msg[1]);
}