JavaScriptLesson 9 of 16

Objects

An object keeps everything about one thing in one place: a character has a name, a level and skills. Each value sits under its own key.

Key points

  • { name: "Luna", level: 3 } is an object made of key: value pairs
  • hero.name and hero["name"] read a property; a missing one gives undefined
  • hero.city = "…" adds a property, hero.level += 1 changes one
  • A method is a function inside an object, and this inside it points to the object
  • Object.keys(obj) returns an array of keys, "key" in obj checks whether a key exists

Example

const book = { title: "Dune", year: 1965, pages: 412 };console.log(book.title, book["year"]); book.rating = 5;console.log(book); for (const key of Object.keys(book)) {  console.log(`${key} → ${book[key]}`);}console.log("author" in book, book.author);

rating was added after the object was created, which is fine. The loop over Object.keys visited every key in order, and the book has no author, hence false and undefined.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Level up the hero: raise level by 1, add the property city with the value Riverwood and the skill alchemy to skills, and make describe() return Luna (level 4) from Riverwood. Output: Luna (level 4) from Riverwood, Skills: stealth, archery, alchemy and name, level, skills, describe, city.

Output

What your program prints appears here.