Go to "next" iteration in JavaScript forEach loop [duplicate] - javascript

This question already has answers here:
"continue" in cursor.forEach()
(7 answers)
Closed 7 years ago.
How do I go to the next iteration of a JavaScript Array.forEach() loop?
For example:
var myArr = [1, 2, 3, 4];
myArr.forEach(function(elem){
if (elem === 3) {
// Go to "next" iteration. Or "continue" to next iteration...
}
console.log(elem);
});
MDN docs only mention breaking out of the loop entirely, not moving to next iteration.

You can simply return if you want to skip the current iteration.
Since you're in a function, if you return before doing anything else, then you have effectively skipped execution of the code below the return statement.

JavaScript's forEach works a bit different from how one might be used to from other languages for each loops. If reading on the MDN, it says that a function is executed for each of the elements in the array, in ascending order. To continue to the next element, that is, run the next function, you can simply return the current function without having it do any computation.
Adding a return and it will go to the next run of the loop:
var myArr = [1,2,3,4];
myArr.forEach(function(elem){
if (elem === 3) {
return;
}
console.log(elem);
});
Output: 1, 2, 4

just return true inside your if statement
var myArr = [1,2,3,4];
myArr.forEach(function(elem){
if (elem === 3) {
return true;
// Go to "next" iteration. Or "continue" to next iteration...
}
console.log(elem);
});

Related

Is there a way to splice out elements of an array and return the spliced array in one line? [duplicate]

This question already has answers here:
Js remove element from array without change the original
(4 answers)
Closed 13 days ago.
If I have an array a = [1,2,3,4] and I want to return it with the 3 removed, there are two ways I can do it:
let b = [...a] // or a.slice()
b.splice(2,1)
return b
or
return [...a.slice(0,2), ...a.slice(3,4)]
Advantage of the second is that it's one line. Disadvantage is that it's verbose. I thought of writing a helper function that contains the logic of the first approach, so that I'd be able to call it in one line elsewhere.
Is there an alternative? Something like splice but that returns that spliced array rather than mutating it and returning the spliced-out elements.
Since you know the indicies you want to remove, you can use the Array.prototype.filter method.
const a = [1,2,3,4];
const b = a.filter((_, i) => i !== 2);
console.log(b);
If you need to remove a range, you can just do something like 2 < i || i > 3.
.filter makes a copy of the array, copying the values where the callback function evaluates truthy and ignores the values where the callback function evaluates falsy.

What does this for loop syntax mean? [duplicate]

This question already has answers here:
Why does this 'for(;;)' loops?
(3 answers)
Closed last month.
I recently came to this thread, and had a quick question on the syntax used in the first answer. #ggorlen used this syntax/notation in the for loop that I've never seen before and couldn't find any answers online:
for (;;) {
try {
await page.waitForFunction(
`${thumbs.length} !==
document.querySelectorAll("#video-title").length`,
{timeout: 10000}
);
}
catch (err) {
break;
}
thumbs = await page.$$eval("#video-title", els => {
els.at(-1).scrollIntoView();
return els.map(e => e.getAttribute("title"));
});
}
What does the for(;;) {...} do?
Thanks!
I just have a question on the syntax used, and couldn't find an answer.
for(;;) {
}
is the equivalent of
while (true) {
}
a normal "for" loop contains 3 parts separated by semi-colons like for(initialization; condition; afterthought)
The initialization runs before the looping starts.
The condition is checked at the beginning of each iteration, and if it evaluates to true, then the code in the loop body executes.
The afterthought is executed at the end of each iteration of the loop.
It is allowed to ommit these parts of the for expression e.g. for(;;)
When omitted it essentially means that it will loop forever since the condition is not present or until the code reaches a return or break.
You can read more about the for function checkout this MDN page.

why JS for loop doesn't work if i put return keyword? [duplicate]

This question already has answers here:
Does return stop a loop?
(7 answers)
Closed 3 years ago.
when i put the return keyword like this example:
for (let z = 0; z < 5; z++) {
return console.log('one');
}
//the result is : 'one'
but when i remove the return keyword like this example:
for (let z = 0; z < 5; z++) {
console.log('one');
}
//the result is : 'one', 'one', 'one', 'one', 'one'
the loop works and return five 'one'
what's the reason for that ?
return returns the value, ending the function immediately.
It doesn't start the next iteration of the loop because that is part of the function (which you've returned from).
The loop is a statement, it says "do {thing} for some number of times based on a condition". But if you return, you are telling the loop to stop, to immediately exit and give you whatever you are returning.
In this case, console.log doesn't do anything directly, it just prints to the console as a side effect. It isn't returning anything.
It doesn't resolve to a value, so what you're doing in the first example is actually returning undefined after one iteration of the loop (and console.log still prints that one value to the console, as you've noticed).

How create a foreach loop to print array in reverse? [duplicate]

This question already has answers here:
Javascript - Loop through array backwards with forEach
(10 answers)
Closed 3 years ago.
I need create a function that prints an array in reverse. The array is:
var array = [1,2,3,4,5]
My attempt is:
function printReverse(){
for (i = array.length ; i >= 0;i--){
console.log(array[i]);
}
}
So i wonder if you can create the same think with foreach.
I could not find anything in the web about it
forEach will strictly 'enumerate' forward through the array, but the callback to forEach will be passed three arguments: the current item, the index of that item, and a reference to the original array. You can use the index to walk backwards from the end. For example:
var array = [1, 2, 3, 4, 5];
array.forEach((_, i, a) => console.log(a[a.length - i - 1]));
Another trick is to use reduceRight to enumerate the items in reverse. The callback here will be passed an accumulator as the first argument (which you can simply ignore) and the item as the second argument. You'll have to pass in a value to initialize the accumulator as well, but again it doesn't really matter what that value is since you'll be ignoring it in this case:
var array = [1, 2, 3, 4, 5];
array.reduceRight((_, x) => console.log(x), 0);

In a nested-loop JS function, does 'return' exit the loop, or the whole function? [duplicate]

This question already has answers here:
What's the best way to break from nested loops in JavaScript? [closed]
(18 answers)
Closed 8 years ago.
I have a piece of JavaScript I can't get to work (Euler Project, problem 3), and I have nested loops as part of the solution. If a condition is met, I want to exit a child loop, and continue with the parent loop. Should I be using return or break to accomplish this?
I've read the answers here: Best way to break from nested loops in Javascript? but am still confused, especially on the answer that includes an anonymous function as part of the solution.
return always exits the current function.
If you need to exit a loop you should be using break which terminates the current loop, label or switch statement.
break exits the loop, and return exits the function, BUT... in javascript you can freely nest them, so you can have a function in a loop in a function in a loop etc. In this case, return terminates its nearest function and not the outer one. Example:
function foo() {
for(var i = 0; i < 5; i++) {
var bar = function() {
// whatever
return;
}
bar();
// after 'bar' returns, we're here and the loop goes on
}
}
PS I'm wondering why you need nested loops for Euler3... could you post your code?
To exit a loop use always the keyword break, unless you determine something inside the loop that makes you decide to exit the whole function, and in that case you use return keyword.
The link you posted, about an anonymous function is ingenious, that solution has 3 loops, but depending on a condition the programmer wants to exit the 2 inner loops simultaneously, but not the outer most, so he wrapped the 2 inner loops inside an anonymous function that executes for each iteration of the outer loop, so that when he decides to break the 2 inner loops, he can call return without exiting the outer most.
Regards.

Categories

Resources