Objects

Read, change, add and delete properties, give an object a method, and see two names share one object.

JavaScript · beginner · 6 min · 10 steps · free

What you'll learn

Objects.js

const book = {
  title: 'Dune',
  pages: 412,
  describe() {
    return `${this.title}, ${this.pages} pages`;
  },
};

book.pages = 420;
book.year = 1965;
const alias = book;
alias.title = 'Dune Messiah';
delete book.year;
console.log(book.describe());
console.log('pages' in book, Object.keys(book));

Step by step

  1. book points to a new object with two properties and a method.
  2. pages in the Object that book points to changes from 412 to 420.
  3. A new key year with the value 1965 is added to the Object that book points to.
  4. alias = book shares the same object, like with arrays.
  5. title in the Object that book and alias point to changes from "Dune" to "Dune Messiah".
  6. The key year is removed from the Object that book and alias point to.
  7. book.describe() calls the method with this set to book.
  8. describe returns "Dune Messiah, 420 pages".
  9. describe() has finished, so its variables are gone. It prints Dune Messiah, 420 pages.
  10. "pages" in book checks for a key; Object.keys lists them.

Common mistakes

Best practices

Key takeaways

Check yourself

{ a: 1 }.b is?

Answer: undefined

Object.keys({ x: 1, y: 2 })?

Answer: ["x", "y"]

·

More in Objects and Arrays