0

I am receiving this error in my console. Error is happening within my for loop Not sure why but when I console.log(manchesterUnited.[0].salary); I get not errors. I am new to JS so it could be something minor. Uncaught TypeError: Cannot read property 'salary' of undefined.

var footballer = function(name, position, age, salary, number) {
  this.name = name;
  this.position = position;
  this.age = age;
  this.salary = salary;
  this.number = number;
}

var manchesterUnited = [];
manchesterUnited[0] = new footballer("Zlatan", "striker", 37, 20, 9);
manchesterUnited[1] = new footballer("Rooney", "forward", 33, 15, 10);

var totalSalary = 0;

for(var i = 0; i <= manchesterUnited.length; i++){
    totalSalary = manchesterUnited[i].salary + totalSalary;
}

console.log(totalSalary);

Thank you.

2 Answers 2

2

In the for loop, you have:

i <= manchesterUnited.length

It should just be:

i < manchesterUnited.length
Sign up to request clarification or add additional context in comments.

1 Comment

You might add the explanation that indicies start at 0 and thus the last element will be at array.length - 1.
0

You need to change this

     for(var i = 0; i <= manchesterUnited.length; i++){
           totalSalary = manchesterUnited[i].salary + totalSalary;
     }

To this

      for(var i = 0; i < manchesterUnited.length; i++){
            totalSalary = manchesterUnited[i].salary + totalSalary;
      }`

The reason being that the <= operator causes you to pass beyond the length of your array by 1.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.