0

I have this class Programmer extends Person and this function is stored inside the class

code () {console.log (`${this.name} is coding`)}

I then created an array outside of the class declaration

const programmers = [new Programmer("dom", 56, 12), new Programmer("jeff", 24, 4)]

And also a function

function developSoftware (programmers) {
    for (let programmer in programmers) {
        programmer.code()
    }
}

Why does the error programmer.code is not a function when I use a for-in loop instead of a for-of loop? what's the logic behind? I know that for arrays one should use a for-of loop

Also how do I format the code in StackOverflow such that the post shows line breaks in between the code?

class Programmer
{
  code () {
    console.log (`${this.name} is coding`);
  }
}

const programmers = [new Programmer("dom", 56, 12), new Programmer("jeff", 24, 4)]

function developSoftware (programmers) {
  for (let programmer of programmers) {
    programmer.code()
  }
}

developSoftware(programmers);
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
nubprog
  • 35
  • 10
  • 2
    I've added a snippet for you with the code you included, though I don't have the Person class that your class extends, so I removed that bit. There is no `.code() is undefined` error. – Liftoff Aug 21 '21 at 08:24
  • programmer doesnt extend person is this example. – The Fool Aug 21 '21 at 08:26
  • there is no error because the code i posted uses the for-of loop, which i asked why the for-in loop doesnt work here – nubprog Aug 21 '21 at 08:26
  • 1
    Oh I misunderstood your question then. `for in` gets the key, where `for of` gets the value. So in the loop `for(let p in programmers)`, `p` is the index of the array, so it would be `programmers[p]` in that case. – Liftoff Aug 21 '21 at 08:27
  • 1
    `for in` returns the enumerator of the item so 0, 1, 2, 3 `for of` retuns the item itself. If you use `for in` you still need to use that number as index to get the item out of the array. – The Fool Aug 21 '21 at 08:27

1 Answers1

1

So Your question is What is Difference for..in and for..of:

Based on this:

  1. for..in iterates over all enumerable property keys of an object
  2. for..of iterates over the values of an iterable object. Examples of iterable objects are arrays, strings, and NodeLists.
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42