Lesson Objectives
By the end of this lesson, you will be able to:
- Create and access object properties.
- Iterate over arrays with
.forEach()
,.map()
, and.filter()
. - 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
:
-
Declare an array of objects:
const contacts = [ { name: 'Alice', phone: '123-456' }, { name: 'Bob', phone: '987-654' }, ]
-
Render a
<ul>
of<li>
items showingname: phone
. -
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
- How do objects and arrays differ in how you access their data?
- When would you choose
.map()
vs.forEach()
? - 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.