This article will demonstrate how the forEach is different from the for loop in TypeScript.
How is “forEach” Different From “for” Loop in TypeScript?
In TypeScript, “forEach” and “for” loops are two different techniques to iterate over arrays or other iterable objects. The main difference between both of these is that a “for” loop is a general-purpose loop that allows performing any operation on array elements, while “forEach” is a method that is designed specifically for iterating over arrays and executing a function for each element. Some common differences will discuss in the given table:
forEach | for loop |
---|---|
The syntax of forEach is more concise and readable. | for loops have a more complex syntax than forEach, which can make them harder to read and understand. |
It is generally more performant than using a for loop, especially for larger arrays. | Overall better performance but less than forEach. |
forEach is designed explicitly for executing a function on each element. | It can perform any operation on each element of an array. |
It is less flexible than for loops. | for loops are more flexible than forEach. |
Before proceeding to the practical implementation, keep in mind that in order to execute a TypeScript file, it must be transpile into a JavaScript file and then run the JavaScript code on the terminal using the given commands:
node filename.js
How Does “forEach” Work in TypeScript?
The “forEach” is a pre-built method in TypeScript that permits us to loop over an array and execute a function on each array element.
Syntax
The following syntax is utilized for the forEach loop:
Example
Create an array of odd numbers:
Iterate the array and print the array elements on the console using the forEach method:
console.log(numbers);
});
Output
]
How Does “for” Loop Work in TypeScript?
A “for” loop is a standard loop. It allows for iterating through a collection of items and performing some actions/operations on each item.
Syntax
The given syntax is utilized for the “for” loop:
// loop body
}
Example
Iterate the above-created array using for loop and display array elements on the console:
console.log(oddNumbers[i]);
}
Output
We have compiled all the necessary instructions relevant to the difference between forEach and for loop in TypeScript.
Conclusion
The “forEach” and “for” loops are two different techniques to iterate over arrays or other iterable objects. While both approaches loop through the array elements, they differ in syntax and functionality. The main difference between both of these is that a “for” loop is a general-purpose loop that allows performing any operation on array elements, while “forEach” is a method that is designed explicitly for iterating over arrays and executing a function for each element. This article demonstrated how the forEach is different from the for loop in TypeScript.