Javascript foreach return value

Using Continue in JavaScript forEach()

JavaScript’s forEach() function executes a function on every element in an array. However, since forEach() is a function rather than a loop, JavaScript errors out if you try to use continue :

[1, 2, 3, 4, 5].forEach(v => < if (v % 2 !== 0) < // SyntaxError: Illegal continue statement: no surrounding iteration statement continue; > >);

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() and need to skip to the next iteration, here’s two workarounds.

1. Use return

For practical purposes, return in a forEach() callback is equivalent to continue in a conventional for loop. When you return , you skip the rest of the forEach() callback and JavaScript goes on to the next iteration of the loop.

// Prints "2, 4" [1, 2, 3, 4, 5].forEach(v => < if (v % 2 !== 0) < return; > console.log(v); >);

Using return is the easiest approach, but it isn’t the most idiomatic use of functional programming patterns. Using if and return typically means you’re better off just using a for loop.

Читайте также:  Os path splitext in python

2. Filter Out Unwanted Values

Instead of thinking about how to skip forEach() when a certain condition occurs, functional programming encourages you to instead think about how to filter() out values before calling forEach() . Using if in a forEach() callback makes functional programming purists cringe, because you’re missing the key benefit of using functional patterns: composition.

Instead of using an if statement, just filter() out the values you don’t want forEach() to execute on.

// Prints "2, 4" [1, 2, 3, 4, 5].filter(v => v % 2 === 0).forEach(v => < console.log(v); >);

More Fundamentals Tutorials

Источник

How to Return a Value From a forEach Loop

You can’t make JavaScript’s forEach() function return a custom value. Using return in a forEach() is equivalent to a continue in a conventional loop.

// Prints "2, 4" [1, 2, 3, 4, 5].forEach(v => < if (v % 2 !== 0) < return; > console.log(v); >);

Variable

You can declare a variable before calling forEach() and set the value inside the loop;

let array = [1, 2, 3, 4, 5]; let max = 0; array.forEach((element) => < if (element > max) < max = v; >>); max; // 5

Using reduce()

JavaScript’s reduce() function iterates over the array like forEach() , but reduce() returns the last value your callback returns.

let array = [1, 2, 3, 4, 5]; let initialMax = 0; const max = array.reduce((element, max) => < if (element > max) < return element; > return max; >, initialMax); max; // 5

More Fundamentals Tutorials

Источник

How to return a value from a foreach loop? Javascript

How to return a value from a foreach loop? Javascript

In javascript, forEach is used to execute a function on each element in an array. However, forEach() by default does not return any value. But there are ways by which we can return a value in a forEach() loop.

In this article, we will see how to return value in a forEach() loop and also explore different methods by which we can return a value for a loop instead of using the forEach() function in Javascript.

Using a variable with forEach() method

To return a value in forEach() method, we can use a variable in the loop and once the loop is finished, we can set the values to that variable.

const arr = [1,2,3,4,5] const newVal = [] const results = arr.forEach(el => < newVal.push(el * 2) >) console.log(newVal) 

Here, we have declared a variable (newVal) and then used it to push the multiplied value to it and when the loop is completed, we have console logged the new values in the terminal.

Now, next, we will learn about other javascript methods that we can use to return a value from a loop.

Using find() method

The find() method in Javascript returns the value of the first element in an array that passes a test function.

We can use this method instead of forEach() to return the first value of a given condition.

const arr = [1,2,3,4,5] const results = arr.find(el => < return el % 2 == 0 >) console.log(results) // output: 2 

In the above example, it returns the first number which is an even number from the given array.

Using reduce() method

The reduce() method iterates over all the elements of an array like forEach method and returns the last value that passes the test condition.

The reduce() method runs a function against an accumulator and each element from left to right in the array to reduce it to a single value.

arr.reduce(callback(accumulator, currentValue), initialValue) 

initialValue is optional. Learn more about it here: Array.prototype.reduce() — JavaScript | MDN

const arr = [2, 5, 5]; const initVal = 0 const result = arr.reduce((total,num) => < return total + num; >) console.log(result) // output: 12 

Here, we loop through the given array and returned the total as the result.

Using map() method

The map() method creates a new array with all the elements of a given array that passes the test function.

We can use this method to return an array of elements that satisfy a certain condition, instead of using the forEach() method.

Array.map(function(element) < if(condition) return element; >); 
const arr = [2, 5, 5]; const result = arr.map(el => < return el * 2 >) console.log(result) //output: [ 4, 10, 10 ] 

Here, we have used map() to loop through each element and multiplied it by 2, and return the new value.

Here, we have learned how we can return a value in forEach() loop and also learned about other methods that can return a value from a loop in Javascript.

Источник

The Right Way to Break from forEach in JavaScript

The Right Way to Break from forEach in JavaScript

How can you break and return from a forEach loop in JavaScript? The short answer is: you can’t. Breaking from forEach loops in JavaScript is not possible. However, there are some workarounds, and there are also alternatives.

While we cannot break and return from a forEach in JavaScript, we can still return values with an external variable in the following way:

let productDetails products.forEach(product =>  if (product.id === 123)  productDetails = product > >)

Here we essentially set a variable outside of the forEach loop to one of the items, based on an ID. Given the right condition inside an if statement, we can grab and «return» the correct value. However, this can be rewritten in better ways. Here are five different alternatives you can use when you need to break from a forEach .

Get your weekly dose of webtips

Level up your skills and master the art of frontend development with bite-sized tutorials.

We don’t spam. Unsubscribe anytime.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.

Using Array.find

The above example can be also rewritten with the find method. As the name suggests, the find method is used for finding a specific element in an array. It returns one item that first passes the test in the callback function. For example:

// This will return the product with the ID of 1 products.find(product => product.id === 1) // Even though we might have multiple products which are on sale // this will only return the first match products.find(product => product.onSale) // This will return undefined products.find(product => product.id === 'invalid')

For the first example, we have one object returned as each ID is unique. But in the second one, we might have multiple products that are on sale, but we still get back only the first one that passes the test. If there is no match, the find method simply returns undefined .

Using Array.findIndex

A similar but slightly different solution to find is using the findIndex method. In case you need to return the index of the element inside an array, you can use the findIndex method. This will return the index of the element if found. If no element is found with a predicate, it will return -1.

// This will return 2 [1, 2, 3].findIndex(number => number === 3) // This will return -1 [1, 2, 3].findIndex(number => number === 4)

Get your weekly dose of webtips

Level up your skills and master the art of frontend development with bite-sized tutorials.

We don’t spam. Unsubscribe anytime.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.

Using Array.some for Returning True or False

In case you need to break from a loop and return a boolean, we can use the some method. Unlike find where we expect an item to be returned from the array, some returns either a true or false . If at least one item in the array matches the criteria, this method will instantly return true . Take the following as an example.

// We do have some products which are on sale so we get back true products.some(product => product.onSale) // None of the items are less than 0, so we get back false [1, 2, 3].some(item => item  0) 

In the first example, we get back true as we are only interested in whether there is at least one item on sale. Likewise, in the second example, we are only interested in whether at least one item is below 0. Since none of them are below 0, the method returns false .

Using Array.every for Checking Every Element

every is very similar to some in terms of the value returned: either return a true or false . But instead of checking if a single item passes the predicate, it will only return true if all items pass the test. Let’s have a look at an example.

// This produces false products.every(product => product.onSale) // This produces true products.every(product => product.name)

In the first example, we get back false as possibly not every product is on sale. However, we can check if every product has a name, in which case every would produce a true value.

Get your weekly dose of webtips

Level up your skills and master the art of frontend development with bite-sized tutorials.

We don’t spam. Unsubscribe anytime.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.

Using Regular Loops

Last but not least, we can also use regular loops which support the break and continue statements. In the below example, we use a regular for , a for. of , and while loop to demonstrate how to break when a statement is true .

const array = [1, 2, 3] // Using a for loop for (let i = 0; i  array.length; i++)  if (array[i] === 2)  break > console.log(array[i]) > // Using a for. of loop for (const item of array)  if (item === 2)  break > console.log(item) > // Using a while loop let i = 0 while (i  array.length)  if (array[i] === 3)  break > console.log(i) i++ >

If you would like to learn more about other array methods too, such as map , filter or reduce , make sure you check out our article below.

How to Open Any File in Javascript with Progressbar

The Power of Higher-Order Array Functions find, some, map, reduce, every, filter Learn everything you need to know about higher-order array methods, and how you can use them to their full potential. Learn More

Get your weekly dose of webtips

📚 More Webtips

Level up your skills and master the art of frontend development with bite-sized tutorials.

We don’t spam. Unsubscribe anytime.

  • Unlimited access to hundreds of tutorials
  • Access to exclusive interactive lessons
  • Remove ads to learn without distractions

How to Optimize Performance with Promises in JavaScript

How to Optimize Performance with Promises in JavaScript

How to Type Functions in TypeScript

How to Type Functions in TypeScript

How to 3D Flip Images With CSS

How to 3D Flip Images With CSS

Get your weekly dose of webtips

Get access to 300+ webtips 💌

Level up your skills and master the art of frontend development with bite-sized tutorials.

We don’t spam. Unsubscribe anytime.

Источник

Оцените статью