Hi,
I found out there is a wrong solution on exercise 36. b)
Task:
a) Define a list that contains the following values: 6, 4 , 1 , 7 , 2 , 8 , 3 , 9 , 11.
b) Use a for-loop to iterate through all the values in the list and find the smallest
value. Print the smallest value. Do this without using JavaScript’s built-in min
function.
Solution in PDF:
const list = [6, 4, 1, 7, 2, 8, 3, 9, 11];
var smallest = list[0];
for (num in list) {
if (num < smallest) {
smallest = list[num];
}
}
console.log(smallest);
Now if you run this it gives you result 1. Which is the smallest and therefore correct.
However something seemed wrong to me there. So I tried to understand the code and I tested it for different array using the same logic:
const list = [6, 4, 12];
var smallest = list[0];
for (num in list) {
if (num < smallest) {
smallest = list[num];
}
}
console.log(smallest);
And this will give you result 12. Which is not smallest and is wrong.
The logic above will give you the correct result only if there is a number in array which is smaller than array.length. It simply does not search for the smallest value.
Am I right? Please look at this. Thanks.