Walk an object's keys and read its values.

Iterating Object Keys

object_keys.js
const bonus = 0;
const keys = Object.keys({ pen: 2, pad: 5, ink: 8 });
let total = 0;
for (const k of keys) {
  const price = ({ pen: 2, pad: 5, ink: 8 })[k];
  total += price + bonus;
}

console.log("count=" + keys.length);
console.log("total=" + total);

Follow the Keys

  1. Object.keys returns pen, pad, and ink.
  2. The matching prices are 2, 5, and 8.
  3. The default bonus is 0.
  4. Each loop pass adds price + bonus.
  5. The script prints count=3 and total=15. | key | price | added with bonus 0 | | --- | --- | --- | | pen | 2 | 2 | | pad | 5 | 5 | | ink | 8 | 8 | | total | - | 15 |
object-keys `Object.keys` returns an array of an object's property names. Looping those keys reads each value, here summing them into a total.

Exercise: object_keys.js

Reproduce count=3 and total=15, then use the pinned bonus variants 10 and 100 to predict totals 45 and 315.