New to JS, can't seem to make this code do what I want.

javascript is not java and if you try it like other language you gonna have a very bad time.

there is so much things to talk about in your code.

first you dont need to declare variables like that you can create a new array literal like this.

var array = [1,2,3];

no need to initilize it. and unlike const when use of var all variables are hoisted and is a good practice define all vars at the top of the scope.

other good practice when use <script> tags is define it at the bottom of body.

i would refactor your code like this:

<code> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Services average</title> </head> <body> <select id="service"> <option value="none">Select Service</option> <option value="carpentry">Carpentry</option> <option value="fencing">Fencing</option> <option value="doors">Doors</option> <option value="windows">Windows</option> <option value="drywall">Drywall</option> <option value="electrical">Electrical</option> </select> <h4 id="avg"></h4> <script> var services = { carpentry: [ 20.33, 30.43, 20.90 ], fencing: [ 45.66, 87.56, 34.55 ], doors: [ 66.66, 36.75, 23.57 ], windows: [ 56.32, 78.89, 34.67 ], drywall: [ 84.74, 43.46, 45.24 ], electrical: [ 46.35, 90.34, 34.35 ] }

  document.getElementById("service").addEventListener("change", function(e){
    if(e.target.value === "none") return document.getElementById("avg").innerHTML = "";
    var sum = services[e.target.value].reduce(function(a,b){ return a+b })
    var avg = Math.round(sum/services[e.target.value].length * 100)/100;
    document.getElementById("avg").innerHTML = " The average price for " +e.target.value+ " is: " + avg;
  });

</script>

</body> </html> </code>

/r/javascript Thread