Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

222
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda