user6035846
user6035846

Reputation:

Javascript with callback function not working

Here is my javascript program and it supposed to output the alert statement at the bottom of the code but is not apppearing. Why is it?

//function mean
function mean(values, callback) {
    var total = 0;
    for (var i = 0, max = values.length; i < max; i++) {
        if (typeof callback === "function") {
            total += callback(value[i]);
        } else {
            total += values[i];
        }
    }
}

var result = mean([2, 5, 7, 11, 4], function (x) {
    return 2 * x;
});

alert("The result mean is " + result + ".");

Upvotes: 1

Views: 102

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386550

You need to return total and change valueto values.

function mean(values, callback) {
    var total = 0;
    for (var i = 0, max = values.length; i < max; i++) {
        if (typeof callback === "function") {
            total += callback(values[i]);
        } else {
            total += values[i];
        }
    }
    return total;
}

var result = mean([2, 5, 7, 11, 4], function (x) {
    return 2 * x;
});

alert("The result mean is " + result + ".");

You can rewrite the code to a more compact way:

function mean(values, callback) {
    callback = callback || function (x) { return x; };
    return values.reduce(function (r, a) {
        return r + callback(a);
    }, 0);
}

var result = mean([2, 5, 7, 11, 4], function (x) {
    return 2 * x;
});

alert("The result mean is " + result + ".");

Upvotes: 3

Jonh Doe
Jonh Doe

Reputation: 761

You have to return total in your callback function and make sure values variables are not typed as value.

Upvotes: 0

AdamCooper86
AdamCooper86

Reputation: 4227

Along with the typo mentioned by Pointy, If I am reading it right, you never return a value from mean, try returning total

Upvotes: 2

Related Questions