Javascript forEach() Array Method

How to use the javascript forEach() array method.

How to use the javascript forEach array method.png

Below shows a typical use of the array method forEach. Note use of the arrow function. If the arrow function contains only one statement, the curly brackets and return keyword can be omitted as shown below.

Additionally a template literal is used below with a placeholder ${user} adding to the terseness of the code. Note that back-ticks (`) are used to denote a template literal.

const users = ['john','derek','tracey','anna'];
users.forEach(user => console.log(`Hello ${user}, welcome!`));

Output will be:

Hello john, welcome!
Hello derek, welcome!
Hello tracey, welcome!
Hello anna, welcome!

Author