loading...

How to break out of the forEach in Javascript/NodeJS

pookdeveloper profile image pookdeveloper ・1 min read

It’s simple.

Use “some” or “every” instead of “forEach”

Use of Array.prototype.some

The some() method checks if at least one element of the array meets the condition implemented by the function provided.

Example:

The result should look like:

1
2
"Result:" true

More info: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/some


Use of Array.prototype.every

The every() method returns a Boolean, true if all the elements in the array pass the condition implemented by the given function and false if one does not fulfill it.

Example:

The result should look like:

1
2
“Result:” false

More info: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/every

That’s all folks

Discussion

pic
Editor guide