What Does 'Return' Keyword Mean Inside 'Foreach' Function

What does `return` keyword mean inside `forEach` function?

From the Mozilla Developer Network:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

  • A simple loop
  • A for...of
    loop
  • Array.prototype.every()
  • Array.prototype.some()
  • Array.prototype.find()
  • Array.prototype.findIndex()

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

Can forEach in JavaScript make a return?

You can use indexOf instead https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

function fn(array) {
return (array.indexOf(2) === -1);
}

Also from the documentation for forEach - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Note: There is no way to stop or break a forEach() loop other than by
throwing an exception. If you need such behaviour, the .forEach()
method is the wrong tool, use a plain loop instead.

So, the return value cannot be used the way you are using it. However you could do a throw (which is not recommended unless you actually need an error to be raised there)

function fn(array) {
try {
array.forEach(function(item) {
if (item === 2) throw "2 found";
});
}
catch (e) {
return false;
}

return true;
}

How to return a value from forEach

forEach() throws away return values and always returns undefined

so no matter what you do inside your code the return value from forEach is never returned

You can create a flag that sets to false when your condition is met(Its a suggestion if you want to go with ForEach)

function isUniform(array) {
let flag=true;
let uniChecker = array[0];
array.forEach(function(element) {
if (uniChecker !== element) {
flag=false;
}
});
return flag;
}

How to use forEach loop to return true if there is condition here in JavaScript

One option you have is to use some to check if atleast one element of array element is the username and password

var database = [{"username":"candy","password":"666"},{"username":"abby","password":"123"},{"username":"bob","password":"777"}];

function checkDatabase2(username, password) {

return database.some(o => o.username == username && o.password == password);

}

console.log(checkDatabase2("bob", "777"));

console.log(checkDatabase2("bob", "NOT777"));

return statement in forEach won't stop execution of function

Old ways are sometimes the best. It's because you're passing a delegate function when calling .forEach. The return within the delegate is getting lost, and isn't applying to anything. To get your desired result, you'll want to exit the calling function addPacking. This can be done using a simply for loop.

function addPacking(item){
for (var i = 0; i < data.packings.length++; i++) {
if (item.name == data.packings[i].name) {
return;
}
}

data.packings.push(item);
});

This approach also supports older browsers, unlike some, every and forEach

For and Foreach loop and return with Set. First recurring number in array

In fact the problem with .forEach() method is that its callback function always return undefined, even if you use a return statement.

If you check the forEach() method MDN reference you can see that:

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.

So in your case return el; inside forEach() callback is always ignored, and inside the forEach callback return is specific to this scope that's why the function won't return anything.

Solution:

If you want to do it with forEach(), what you can do is to store this flag in a variable so you can return it after the forEach() block:

const recurring = (arr) => {

const set = new Set();
let result;
arr.forEach(el => {
if (set.has(el)) {
result = !result ? el : result;
return;
} else {
set.add(el);
}
});
return result;
}

Demo:

const arr1 = [2, 2, 3, 2, 5, 6, 6, 9];

const recurring = (arr) => {

const set = new Set();

let result;

arr.forEach(el => {

if (set.has(el)) {

result = !result ? el : result;

return;

} else {

set.add(el);

}

});

return result;

}

console.log(recurring(arr1));

Why does this forEach return undefined when using a return statement

The function e() isn't returning anything; the inner anonymous function is returning its e value but that return value is being ignored by the caller (the caller being function e() (and can the multiple uses of 'e' get any more confusing?))

What does `return` keyword mean inside `forEach` function?

From the Mozilla Developer Network:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

  • A simple loop
  • A for...of
    loop
  • Array.prototype.every()
  • Array.prototype.some()
  • Array.prototype.find()
  • Array.prototype.findIndex()

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

Why would for loop and forEach work different?

Return statement is equivalent of break, for loop can be broken, foreach can't be.



Related Topics



Leave a reply



Submit