×

javascript · level 2 · unit 5 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

lists an object's keys, ready for a loop.

Object.keys(pet) hands back an array of the object's keys, in the order they were written: ["name", "age", "toy"]. Loop over it with for...of and you visit every key, even ones you did not know were there.

Inside the loop, pet[key] looks up each value with bracket notation. Together they turn any object into a list on the page, one item per key.

<h2>Pet profile</h2>
<ul id="profile"></ul>
const pet = { name: "Rex", age: 3, toy: "squeaky ball" };
const profile = document.querySelector("#profile");
for (const key of Object.keys(pet)) {
  const item = document.createElement("li");
  item.textContent = `${key}: ${pet[key]}`;
  profile.append(item);
}

Press run it to bring the page to life.

console

nothing logged yet

Object.keys belongs to JavaScript itself, which is why it starts with a capital O.