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 :: react tooltip on disabled button 
Javascript :: javascript function page size 
Javascript :: usecontext react 
Javascript :: delete document mongoose 
Javascript :: js cheat sheet 
Javascript :: get in redis 
Javascript :: index of row jquery 
Javascript :: on window resize and on page load 
Javascript :: array map javascript 
Javascript :: create new Next.js 
Javascript :: TypeError: JSON.stringify(...).then is not a function 
Javascript :: isprime js 
Javascript :: escaped json to json javascript 
Javascript :: javascript new line 
Javascript :: js spleep 
Javascript :: await loop javascript 
Javascript :: edit external json file in javascript 
Javascript :: mongodb empty an array field 
Javascript :: google gapi auth2 get current token 
Javascript :: react toggle state 
Javascript :: coffeescript to javascript 
Javascript :: link to website electron 
Javascript :: mongoose updateone example 
Javascript :: multi ternary operation in javascript 
Javascript :: javascript find object in array by property value 
Javascript :: exploding string with comma using jquery 
Javascript :: js map size 
Javascript :: delete from list javascript 
Javascript :: antd tag 
Javascript :: try...catch...throw javascript 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =