Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Why does .forEach() work but not a for loop?

Currently learning Node.JS and making a basic command prompt note application. While working on the listNotes function (meant to display all titles of the notes) I initially started with this:

const notes = loadNotes() 
    for (let note in notes) {
        console.log(note.title)
    }

This left me with an undefined.

However,

const notes = loadNotes()
    notes.forEach((note) => {
        console.log(note.title)
    })

left me with the actual note title.

What is the difference between forEach and and a for loop in this case?

For clarification, all my loadNotes() method is doing is reading a JSON file and parsing it into an object. If file doesn't exist, it creates an empty array

Note can be defined as:

Note[{
title: "string",
body: "string"
}]

Thanks in advance!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should use "of" instead of "in"

ex:

const notes = loadNotes() 
for (let note of notes) {
  console.log(note.title)
}

Like Phil pointed out, for..in will iterate indexes.

Ex, if notes is an array:

const notes = loadNotes() 
for (let index in notes) {
  console.log(index)
}
// outputs are: 0,1,2, etc...
// You are doing something like: 1.title, 2.title
// 'title' is not a field of these numeric values, 
// so you are getting 'undefined' values
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!