Michael Ouroumis logoichael Ouroumis
← Back to course

Objects & Arrays

Learn how to structure data with JavaScript objects and arrays.

Lesson Objectives

By the end of this lesson, you will be able to:

  1. Create and access object properties.
  2. Iterate over arrays with .forEach(), .map(), and .filter().
  3. Combine objects and arrays to model complex data.

1. JavaScript Objects

An object is a collection of key/value pairs:

const user = { name: 'Alice', age: 30, isAdmin: false, } // read console.log(user.name) // "Alice" // write user.age = 31

Dynamic keys

const key = 'role' user[key] = 'editor'

2. Arrays & Iteration

Arrays hold ordered lists:

const fruits = ['🍎', '🍌', '🍇'] // forEach fruits.forEach((fruit, idx) => console.log(idx, fruit)) // map → new array const lengths = fruits.map((f) => f.length) // filter → subset const startsWithA = fruits.filter((f) => f.startsWith('A'))

3. Nested Structures

You can nest objects and arrays:

const posts = [ { id: 1, title: 'Hello', tags: ['intro', 'js'] }, { id: 2, title: 'Advanced', tags: ['deep', 'js'] }, ] // find first post with tag "intro" const intro = posts.find((p) => p.tags.includes('intro'))

Task: Build a Simple Address Book

In your scaffold/index.js:

  1. Declare an array of objects:

    const contacts = [ { name: 'Alice', phone: '123-456' }, { name: 'Bob', phone: '987-654' }, ]
  2. Render a <ul> of <li> items showing name: phone.

  3. Add an input and button that let the user add a new contact—update the contacts array and re‐render the list.

Bonus: Add a “delete” button next to each contact.


Reflection

  1. How do objects and arrays differ in how you access their data?
  2. When would you choose .map() vs .forEach()?
  3. How can nested structures help model real-world data?

Next Steps: Try combining .filter() on your address book to show only contacts whose names include a given letter.

Try It Yourself

const listEl = document.getElementById('list')
const nameEl = document.getElementById('name')
const phoneEl = document.getElementById('phone')
const addBtn = document.getElementById('addBtn')

// initial data
const contacts = [
  { name: 'Alice', phone: '123-456' },
  { name: 'Bob', phone: '987-654' },
]

// render helper
function render() {
  listEl.innerHTML = ''
  contacts.forEach((c, i) => {
    const li = document.createElement('li')
    li.textContent = `${c.name}: ${c.phone}`
    // bonus: delete button
    const del = document.createElement('button')
    del.textContent = '✖'
    del.style.marginLeft = '0.5rem'
    del.onclick = () => {
      contacts.splice(i, 1)
      render()
    }
    li.appendChild(del)
    listEl.appendChild(li)
  })
}

addBtn.addEventListener('click', () => {
  const name = nameEl.value.trim()
  const phone = phoneEl.value.trim()
  if (name && phone) {
    contacts.push({ name, phone })
    nameEl.value = phoneEl.value = ''
    render()
  }
})

// initial render
render()