0

In order to iterate a map in Typescript.

The forEach won't be interrupted. Strangely the key and value have to be inverted.

The for works correctly.

    const map = new Map<number, number>()
    const uniq = new Set<number>();

    // won't return anything if condition is true
    map.forEach( (v,k) => { // moreover , k and v are inverted 
        if(uniq.has(v)) return false
        uniq.add(v)
    });

    // will work
    for (const [_, v] of map.entries()) {
        if(uniq.has(v)) return false
        uniq.add(v)
    }

Why forEach doesn't break or return ?

Raymond Chenon
  • 11,482
  • 15
  • 77
  • 110
  • 1
    Edit : found it `There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?v=example – Raymond Chenon Nov 30 '22 at 11:16
  • "*Why forEach doesn't break or return ?*" because that's how `.forEach()` works, which is behaviour not at all related to maps. – VLAZ Nov 30 '22 at 11:18

1 Answers1

1

The .forEach method accept a function as argument that will be called on each element of the iterable.

The return keyword ends the current execution of it's function, this is why you can't exit from a forEach with a simple return, it will exit only the current function call with the element, it won't exit the forEach.

Nullndr
  • 1,624
  • 1
  • 6
  • 24