1

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 + ".");
6
  • 4
    total += callback(value[i]); -- should be values not value. Keep your browser console open so that you can see errors reported. Commented Mar 15, 2016 at 16:40
  • Value is not defined Commented Mar 15, 2016 at 16:42
  • check your console for errors in JavaScript Commented Mar 15, 2016 at 16:43
  • You have to write values[i] and return the variable total in order to get a result other than undefined., Commented Mar 15, 2016 at 16:43
  • 2
    You can answer that question yourself if you learn how to debug JavaScript. Stack Overflow is not a debugging service. Commented Mar 15, 2016 at 16:46

3 Answers 3

3

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 + ".");

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.