Why doesn't this simple JavaScript program work?

Viewed 63

I'm trying to display the minimum, the maximum and the mean from an array of numbers entered by the user.

The Console of the browser tells me that min() and max() aren't functions
Error displayed :

Uncaught TypeError: max is not a function
at HTMLInputElement.onclick (numbers.html:7)
onclick @ numbers.html:7

Only the mean function works, the others don't ... why??

var i;
var num = new Array();
window.alert("enter 10 numbers:");
for (i = 0; i < 10; i++) {
  num[i] = parseInt(prompt("num"));
}

function max() {
  var max = num[0];
  for (i = 0; i < 10; i++) {
    if (max < num[i]) {
      max = num[i];
    }
  }
  window.alert("the max is: " + max);
}

function min() {
  var min = num[0];
  for (i = 0; i < 10; i++) {
    if (min > num[i]) {
      min = num[i];
    }
  }
  window.alert("the min is: " + min);
}

function mean() {
  var mean = 0;
  for (i = 0; i < 10; i++) {
    mean += num[i];
  }
  mean = mean / 10;
  window.alert("mean : " + mean);
}
<!DOCTYPE html>
<html>

<head>
  <title>Numbers</title>
</head>

<body>
  <input type="button" value="max" onclick="max()"><br>
  <input type="button" value="min" onclick="min()"><br>
  <input type="button" value="mean" onclick="mean()"><br>
  <script src="numbers.js"></script>
</body>

</html>

2 Answers

Try to call you functions differently, for example you can call your max function maximum instead and make sure you change it to maximum in your html onclick handler. when you declare a variable with "var" it's declared globally (one good reason why you should avoid doing that and use let and const instead). your code should look like this:

var i;
var num = new Array();
window.alert('enter 10 numbers:');
for (i = 0; i < 10; i++) {
    num[i] = parseInt(prompt('num'));
}
var max;
var min;
function maximum() {
    max = num[0];
    for (i = 0; i < 10; i++) {
        if (max < num[i]) {
            max = num[i];
        }
    }
    window.alert('the max is: ' + max);
}

function minimum() {
    min = num[0];
    for (i = 0; i < 10; i++) {
        if (min > num[i]) {
            min = num[i];
        }
    }
    window.alert('the min is: ' + min);
}

function mean() {
    var m = (max + min) / 2;
    window.alert('mean : ' + m);
}

your html:

 <input type="button" value="max" onclick="maximum()"><br>
 <input type="button" value="min" onclick="minimum()"><br>
 <input type="button" value="mean" onclick="mean()"><br>

Min and max are reserved names change the names of the functions to _min _max

Related