Array in JavaScript
In JavaScript, an array is a special object that provides a way to store and organize data. It is a linear, ordered collection of elements, and an index can access each element. The array object in JavaScript comes with various built-in methods for manipulating and working with arrays.
The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.
Spread operator doing concat
let arrayOne = [1, 2, 3];
let arraryTwo = [4, 5];
arrayCombined = [...arrayOne,...arrayTwo];
Add item using spread operator
let arrayOne = [1, 2, 3];
arrayNew = [...arrayOne, 3];
Arrays are ordered collections of values, and they are perhaps the most commonly used data structure in JavaScript. Elements in an array can be accessed by their index, and arrays can hold values of different data types.
let myArray = [1, 2, 3, 4, 5];
console.log(myArray[0]); // Accessing the first element
JavaScript's forEach() function executes a function on every element in an array. However, since forEach() is a function rather than a loop, using the break statement is a syntax error:
[1, 2, 3, 4, 5].forEach(v => {
if (v > 3) {
// SyntaxError: Illegal break statement
break;
}
});
We recommend using for/of loops to iterate through an array unless you have a good reason not to. However, if you find yourself stuck with a forEach() that needs to stop after a certain point and refactoring to use for/of is not an option, here are four workarounds.
The every() function behaves exactly like forEach(), except it stops iterating through the array whenever the callback function returns a false value.
// Prints "1, 2, 3" [1, 2, 3, 4, 5].every(v => { if (v > 3) { return false; } console.log(v); // Make sure you return true. If you don't return a value, `every()` will stop. return true; });
With every(), return false is equivalent to a break, and return true is equivalent to a continue.
Another alternative is to use the find() function, which is similar but just flips the boolean values. With find(), return true is equivalent to break, and return false is equivalent to continue.
Instead of thinking about how to break out of a forEach(), try thinking about how to filter out all the values you don't want forEach() to iterate over. This approach is more in line with functional programming principles.
The findIndex() function takes a callback and returns the first index of the array whose value the callback returns truthy for. Then the slice() function copies part of the array.
// Prints "1, 2, 3" const arr = [1, 2, 3, 4, 5]; // Instead of trying to `break`, slice out the part of the array that `break` // would ignore. arr.slice(0, arr.findIndex(v => v > 3)).forEach(v => { console.log(v); });
If you can't use every() or slice(), you can check a shouldSkip flag at the start of your forEach() callback. If you set shouldSkip to true, the forEach() callback returns immediately.
// Prints "1, 2, 3" let shouldSkip = false; [1, 2, 3, 4, 5].forEach(v => { if (shouldSkip) { return; } if (v > 3) { shouldSkip = true; return; } console.log(v); });
This approach is clunky and inelegant, but it works with minimum mental overhead. You can use this approach if the previous approaches seem too clever.
The forEach() function respects changes to the array's length property. So you can force forEach() to break out of the loop early by overwriting the array's length property as shown below.
const myNums = [1, 2, 3, 4, 5]; myNums.forEach((v, index, arr) => { console.log(v); if (val > 3) { arr.length = index + 1; // Behaves like `break` } }
While this approach works, it also mutates the array! If you change the array's length, you effectively truncate the array: subsequent operations, like for/of or JSON.stringify() will only go through the shortened version of the array. Using this approach to break out of a forEach() loop is not recommended.
JavaScript's forEach() function executes a function on every element in an array. However, since forEach() is a function rather than a loop, using the break statement is a syntax error.
The some() method of Array instances tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise, it returns false. It doesn't modify the array.
Reference: Array.prototype.some() - JavaScript | MDN (mozilla.org)
Comments