I am trying to create a function that removes the smallest item from a list (dropping the lowest grade in gradeList) to add to a library for the unit 7 project. The function runs as intended but gives me an error in the console.log saying “removeItem() index parameter value (undefined) is not a number” as I am trying to use a variable I defined for the index parameter.
function dropLowest(gradeList) {
var lowest = gradeList[0];
var index;
for (var i = 0; i < gradeList.length; i++) {
if(gradeList[i] < lowest) {
index = i;
lowest = gradeList[i];
}
}
removeItem(gradeList, index);
return gradeList;
}
Is there a better way to do this so that I won’t get an error? Here is the link to my unfinished project: App Lab - Code.org
When you create the variable index, you also have to assign it a value, in this case, a numerical value. If you don’t, the default value will be “undefined”, and your program won’t run properly.
I don’t have a better explanation. I got help myself to find the bug. I am sure other teachers can explain this better than me.
The problem that can happen is when you don’t find a lower grade than the first one. You have saved the value of the lowest grade so far as lowest, but you have not saved the location of that grade in the list. So when you try to use index it is still undefined. So when you initialize lowest to the 0th item in the list you had better initialize index to the location in the list which in this case is 0.
Initializing stuff to 0 happens a lot and it can be easy to not really understand where that zero comes from. Consider this code that makes it more obvious.
function dropLowest(gradeList) {
var indexOfLowest = 0;
for (var i = 1; i < gradeList.length; ++i) {
if(gradeList[i] < gradeList[indexOfLowest]) {
indexOfLowest = i;
}
}
removeItem(gradeList, indexOfLowest);
return gradeList;
}
If you also look at the for loop you will notice I have chosen not to initialize i to 0. I don’t need to check the 0th item. So I don’t. 0 is not a special universal initialization it is meaningful, choose wisely.