Problem with a for loop

Hi there!

I have a newbie question. My task is the following.

There is the array “courses” consisting of a unknown number of arrays with strings that show the students of the course. I want to find out which course in “courses” is the smallest one. My thinking was the following.

// Find out how many courses currently exist
var coursesCount = courses.length

    // Compare the number of students of each course with the next one and filter out the smallest one
    for (var i = 0; i <= coursesCount; i++){
       
        if (i == 0){
            var smallestCourse = courses[i]; 
        }
        else {
            if (courses[i].length < smallestCourse.length){
                smallestCourse = courses[i];
            }
        }
    }

// Tell me what members are in the smallest course

console.log(smallestCourse)

The problem is that I always receive the error message: Uncaught ReferenceError: course is not defined at red line ​

I cannot wrap my head around it. Why should course [i] be undefined since the loop is running all numbers from 0 til the max number of courses?

Ok, so this works:

for (var i in courses){

        let course = courses[i]

   

        if (i == 0){

            var smallestCourse = course.length;

        }



        if (course.length < smallestCourse){

        smallestCourse = course.length;

        }

    }

    console.log(smallestCourse)

But still I do not understand why the other function does not work. So if anyone can explain, I would appreciate it.

1 Like