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 :: javascript variable with multiline text 
Javascript :: install vue js 
Javascript :: radio button group get value javascript 
Javascript :: react script 
Javascript :: react read multiple files with filereader 
Javascript :: javascript count no of lines 
Javascript :: font awesome cdn svg with js 
Javascript :: jest to include text 
Javascript :: change key name in array of objects javascript 
Javascript :: merge array of objects javascript 
Javascript :: loop through an array in js 
Javascript :: how to make a div appear when clicked on in javascript 
Javascript :: js loop trough map 
Javascript :: require a json as a string 
Javascript :: npm install nodemon 
Javascript :: how to create a folder using fs in node js 
Javascript :: path resolve in node js to current dir 
Javascript :: javascript json stringify indented 
Javascript :: stream recording javascript 
Javascript :: add property to all documents mongo 
Javascript :: how to set the development mode in webpack 
Javascript :: dotenv not loading process.env in node 
Javascript :: react render component after fetch 
Javascript :: pass parameter to handleclick react 
Javascript :: form submit event get button 
Javascript :: js loader 
Javascript :: get option value jquery 
Javascript :: datatables server side 
Javascript :: use setstate in function component 
Javascript :: repeat array in js 
ADD CONTENT
Topic
Content
Source link
Name
4+6 =