0

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!

aichex
  • 5
  • 1

1 Answers1

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