Reputation: 19
From my code below, I try to remove a person that does not exist in my array. However, I provided an else statement to render when that person does not exist. I still get a reference error thrown. Can anyone help me out, I'm new to js. thanks.
class Employee {
constructor(name, salary, hireDate) {
this.name = name;
this.salary = salary;
this.hireDate = hireDate;
}
getInfo() {
return `${this.name} $${this.salary} ${this.hireDate}`;
}
}
class Department extends Employee {
constructor(name) {
super();
this.name = name;
this.employees = [];
}
addEmployee(person) {
if (person instanceof Employee) {
this.employees.push(person);
} else {
console.log("The input is invalid");
}
}
removeEmployee(person) {
let index = this.employees.indexOf(person);
if (index > -1) {
this.employees.splice(index, 1);
} else if (index === -1) {
console.log("This person isn't in the department");
}
}
calculateSalary() {
let total = 0;
this.employees.forEach((item) => {
total += item.salary;
});
console.log(total);
}
printAllEmployees() {
this.employees.forEach((item) => console.log(item.getInfo()));
}
}
let accountsDept = new Department("Accounting");
let person1 = new Employee("David", 2000, "01/01/2020");
let person2 = new Employee("Mike", 1800, "04/02/2020");
let person3 = new Employee("Mary", 2100, "04/03/2019");
accountsDept.addEmployee(person1);
accountsDept.addEmployee(person2);
accountsDept.addEmployee(person3);
accountsDept.removeEmployee(person4);
accountsDept.printAllEmployees();
accountsDept.calculateSalary();
Upvotes: -4
Views: 134
Reputation: 944256
If you call removeEmployee
and pass it a value which isn't in this.employees
then you will will the line console.log("This person isn't in the department");
.
You aren't calling removeEmployee
.
accountsDept.removeEmployee(person4);
This line does two things:
person4
removeEmployee
and passes that value to it… except that person4
doesn't exist, so step 1 throws the exception you are seeing and the code never proceeds to step 2.
Upvotes: 0