brld brld - 3 years ago 542
Javascript Question

Javascript unexpected identifier?

I have a function which takes the average of all the elements in an array. However, I am getting an unexpected identifier error.

function calculateAverage(anyArray) {
var sum = 0;
for (int i = 0; i < anyArray.length; i++) {
sum += anyArray[i];
sum = sum / anyArray.length;

I have counted my braces and parentheses and the error seems to be happening only when the for loop is included, as when I removed it the error does not occur.

Solved: I used "int" instead of "var" in my for loop from habit because of other programming language syntaxes.

Answer Source

In your for loop, you are using int, which is not a keyword in javascript, hence the error "Unexpected identifier". You should use var, or let.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download