TypeScript forEach

The forEach() method is an array method which is used to execute a function on each item in an array. We can use it with the JavaScript data types like Arrays, Maps, Sets, etc. It is a useful method for displaying elements in an array.

Syntax

We can declare the forEach() method as below.

array.forEach(callback[, thisObject]);

The forEach() method executes the provided callback once for each element present in the array in ascending order.

Parameter Details

1. callback: It is a function used to test for each element. The callback function accepts three arguments, which are given below.

  • Element value: It is the current value of the item.
  • Element index: It is the index of the current element processed in the array.
  • Array: It is an array which is being iterated in the forEach() method.
Note
Note: These three arguments are optional.

2. thisObject: It is an object to use as this when executing the callback.

Return Value

It will return the created array.

Example with string

Example #1
snippet
let apps = ['WhatsApp', 'Instagram', 'Facebook'];
let playStore = [];

apps.forEach(function(item){
  playStore.push(item)
});

console.log(playStore);

The corresponding JavaScript code is:

snippet
var apps = ['WhatsApp', 'Instagram', 'Facebook'];
var playStore = [];
apps.forEach(function (item) {
    playStore.push(item);
});
console.log(playStore);
TypeScript forEach

Example with number

Example #2
snippet
var num = [5, 10, 15];
num.forEach(function (value) {
  console.log(value);
});
TypeScript forEach

Disadvantage of forEach()

The following are the disadvantages of the use of the forEach() method:

  1. It does not provide a way to stop or break the forEach() loop.
  2. It only works with arrays.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +