Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

foreach break js

var BreakException = {};

try {
  [1, 2, 3].forEach(function(el) {
    console.log(el);
    if (el === 2) throw BreakException;
  });
} catch (e) {
  if (e !== BreakException) throw e;
}
Comment

javascript fore each break example


The for…of loop would be the preferred solution to this problem. It provides clean easy to read syntax and also lets us use break once again. 

let data = [
    {name: 'Rick'},{name: 'Steph'},{name: 'Bob'}
  ]

for (let obj of data) {
  console.log(obj.name)
  if (obj.name === 'Steph') break;
Comment

javascript foreach break

//Use some instead
[1, 2, 3].some(function(el) {
  console.log(el);
  return el === 2;
});
Comment

can i use break in foreach javascript

/* use for...of instead 
Officially, there is no proper way to break out of a forEach loop in javascript.
Using the familiar break syntax will throw an error
If breaking the loop is something you really need, 
it would be best to consider using a traditional loop. */
Comment

PREVIOUS NEXT
Code Example
Javascript :: sum elements in list with same name js 
Javascript :: js print array without comma 
Javascript :: react native floating button 
Javascript :: angular delete with body 
Javascript :: react link without underline 
Javascript :: how to get attr in vuejs 
Javascript :: Too long with no output (exceeded 10m0s): context deadline exceeded 
Javascript :: turn Iterator into array JS 
Javascript :: js largest number in array 
Javascript :: scrolltop in javascript 
Javascript :: javascript easiest way to get second parent 
Javascript :: history push search params 
Javascript :: flatten an array without using .flat(); 
Javascript :: cannot use import statement outside a module 
Javascript :: how to reverse a string in javascript without using reverse method 
Javascript :: axios post 
Javascript :: javascript if browser out of focus 
Javascript :: Get the value of text input field 
Javascript :: how to iterate over list in jquery 
Javascript :: how to get array from number length 
Javascript :: open pdf in browser javascript 
Javascript :: react router dom v6 active link 
Javascript :: virtual dom explained 
Javascript :: react app js 
Javascript :: javascript arrow functions default parameter 
Javascript :: json limit nodejs 
Javascript :: js string to json 
Javascript :: map index 
Javascript :: saving text in javascript 
Javascript :: jquery form data 
ADD CONTENT
Topic
Content
Source link
Name
5+4 =