Date:

Share:

How to use for loops to break out early in javascript?

Related Articles

Answer

for Loop is rarely talked about in modern JavaScript, although it is only useful in asynchronous action scenarios.
But what erupts early consider the following example:
Match two arrays


const smallArray = [0, 2];
const largeArray = Array.from( length: 1000 , (_, i) => i);

const areEqual = (a, b) => 
  let result = true;
  a.forEach((x, i) =>  x !== b[i]) result = false;
  );
  return result;

areEqual(largeArray, smallArray); // false
// Will loop over all items in `largeArray`

The code is not optimized, but it emphasizes the issue of array methods, such as [].forEach() Inability to get out of the loop early.
To neutralize this, we can use a for Early loop return Instead:


...
const areEqual = (a, b) => 
  for (let i in a)  a[i] !== b[i]) return false;
  
  return true;

areEqual(largeArray, smallArray); // false
// Will only loop until the first mismatch is encountered

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles