Hi @Malik & @jott thanks for helping to elaborate on practice #36!
Apologies in advance for the long entry!!
To try and better understand how the for…in loop works, I added a console.log(num) within the for loop as well.
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(num);
}
console.log(smallest);
The output for console.log(num) were the indices. 0, 1, 2…8 of the array.
Questions:
-
Does that mean that the binding num stores both the index of the array and the value? Because it must be storing a value for ‘number < smallest’ to work wouldn’t it?
-
Here’s where I got a little confused, so I changed the script to smallest = num, and the console.log(smallest) outputs 0. This means that num was represented as an index. And if that’s the case, how did ‘number < smallest’ work?
As I was reading up more, I realised we could use a for…of loop for this as well.
const list = [6, 4, 1, 7, 2, 8, 3, 9, 11];
var smallest = list[0];
for (num of list){
if (num < smallest){
smallest = list[num];
}
console.log(num);
}
console.log(smallest);
In this case the console.log(num) output the values, 6, 4, 1…11. So then num < smallest made sense to me.
However, I realised that the script worked regardless of where I use smallest = list[num] or * smallest = num*. Which then got me confused again and it goes back to my earlier questions on top.
Thanks for reading all the way through!
– Chin