Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interrupt/break/stop forEach in ES6 Map?

Is there a nice way (except using JS exceptions) to stop forEach loop in ES6 Map object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach )

From example provided on MDN - is there a way to stop enumeration on 'bar' (skip bar):

function logMapElements(value, key, map) {
    console.log(`m[${key}] = ${value}`);
}
new Map([['foo', 3], ['bar', {}], ['baz', undefined]]).forEach(logMapElements);

For the people who suggest to close this question: yes, it is similar to the questions about Array.prototype.forEach.
But at the same time is different: most of the suggested answers won't work with ES6 set and map. Only throwing the exception will work, but I ask for some other ways

like image 750
vmg Avatar asked Feb 05 '23 21:02

vmg


1 Answers

There is no good reason to use forEach any more in ES6. You should use iterators and for … of loops from which you can ordinarily break:

const m = new Map([['foo', 3], ['bar', {}], ['baz', undefined]]);
for (let [key, value] of m) {
    console.log(`m[${key}] = ${value}`);
}
like image 86
Bergi Avatar answered Feb 07 '23 12:02

Bergi