TL ; DR:
A for...in loop visits every key of an object. Read each value with its key in square brackets.
const stock: { [key: string]: number } = {"apples": 5, "pears": 2};
for (const fruit in stock) {
console.log(fruit, stock[fruit]);
}
// apples 5
// pears 2
Full lesson:
A loop can visit every entry of an object, one at a time. The loop body runs once per key.
for...in gives the keys of an object. Inside the loop, stock[fruit] reads the value of the current key.
You can also get each key with its value in one go. Loop over Object.entries(stock), where each entry is a [key, value] pair.
for (const [fruit, amount] of Object.entries(stock)) {
console.log(fruit, amount);
}
The order: an object keeps word keys, like these names, in the order they were added. Keys that look like whole numbers come first. Many other languages keep no order. A total or a count comes out the same in any order. Those are safe answers.
Watch out: in and of are different. for...of straight on an object fails with "stock is not iterable".
Your task
A game keeps each player's points in scores. The variables total and count start at 0.
Loop over scores. Add every player's points, scores[name], to total. Count the players with 10 points or more in count.
The code at the bottom prints both.
Expected output:
43
2Free plan: 30 tutor messages. PRO is unlimited.
