Introduction
When JavaScript projects grow, it becomes challenging to maintain them. Because JavaScript was never designed for building large-scale applications. Its primary purpose was to provide small scripting functionalities for a web page. Until recently, it did not offer tools such as classes, modules, and interfaces for structuring large projects.
TypeScript uses a .ts extension, in contrast to the .js extension used by JavaScript. TypeScript is a superset of JavaScript, so all valid JavaScript codes are also valid TypeScript codes and renaming a .js file to .ts file won’t change anything.
TypeScript adds static typing and language features such as classes, modules and interfaces. TypeScript is a language for application-scale JavaScript development. In this blog, we will discuss the forEach method used in Typescript to perform various operations on an array.
forEach method in Typescript
The forEach() is an array method used to call a function for each element in an array. It is a useful method for performing operations on arrays, displaying the elements of an array, manipulating its elements etc. We can use them with the JavaScript data types like Arrays, Sets, Maps, etc.
We can declare the forEach() method in typescript as:
Syntax
array.forEach(callback[, thisObject]);
The forEach() method executes a callback once for every element present inside the array in ascending order.
Parameters
- Callback - It is a function used for testing each element.
-
thisObject - This object is used when executing the callback.
Consider the following example
Example 1:
let array = [1, 2, 3, 4, 5]; // printing each element
array.forEach(function (value) {
console.log(value);
});
Output:
1
2
3
4
5
Example 2:
let array = [‘Honda’, ‘Hyundai’, ‘Toyota’];
// printing each element
array.forEach(function(value) {
console.log(value);
});
Output:
[ ‘Honda’, ‘Hyundai’, ‘Toyota’ ]
Return Value
This parameter returns the created array.
Example 1:
let cadbury = ['DairyMilk', 'Temptations', 'Bournville'];
let chocolates = [];
cadbury.forEach(function(item) {
chocolates.push(item)
});
console.log(chocolates);
Output:
['DairyMilk', 'Temptations', 'Bournville']
Example 2:
var number = [10, 20, 30];
number.forEach(function(val) {
console.log(val);
});
Output:
10
20
30