Merge Sort in JS

a simple merge sort with a S ton of logging to help someone learn how it works. This is not memory optimized. See comments on how to optimize.

by Christopher Stephens

HTML

<div id="logger"></div>

CSS

.title {
    font-weight:bold;
    margin-top:15px;
}

JavaScript

// merge sort

// REMOVE these if running in somethign that supports console.log etc
console.log = function (message) {
    $("#logger").append("<div>" + message + "</div");
};
console.debug = function (message) {
    $("#logger").append("<div class='title'>" + message + "</div");
};

var unsorted = [0,3, 6, 4, 5, 8, 1, 7, 9, 2];

// I'm using a closure/module here so that I can declare merge once and not evertime I call the internal sort
var mergeSort = (function () {
    var merge = function (sortedA, sortedB) {
        console.debug("merging");
        console.log(sortedA);
        console.log(sortedB);
        var toReturn = [];
        var itA = 0,
            itB = 0,
            Alength = sortedA.length,
            Blength = sortedB.length;
        while (itA < Alength && itB < Blength) {
            if (sortedB[itB] < sortedA[itA]) {
                toReturn.push(sortedB[itB++]);
            } else {
                toReturn.push(sortedA[itA++]);
            }
        }
        toReturn = toReturn.concat(sortedB.slice(itB)).concat(sortedA.slice(itA));
        return toReturn;
    };
    var sort = function (toSort) {
        var arlength = toSort.length;
        var midpoint = Math.round(arlength / 2);

        if (toSort.length > 1) {
            // just here to illistrate the steps, these should be remove or renamed and moved to the top of the function
            // MEMOP - slicing creates new arrays, performign this in place would be lighter
            var A = toSort.slice(0, midpoint);
            var B = toSort.slice(midpoint, arlength);
            console.debug("slicing");
            console.log("mid:" + midpoint + " to end:" + (arlength - midpoint - 1));
            console.log(toSort);
            console.log(A);
            console.log(B);
            return merge(sort(A), sort(B));
        }
        return toSort;
    };

    return sort;
})();

var result = mergeSort(unsorted);
console.debug("FINISHED");
console.debug(result);