Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

228
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda