The for-each loop is an essential concept in TypeScript and other programming languages. It allows you to iterate through arrays, lists, and other collection data types easily.
In this comprehensive guide, we will dive deep into for-each loops in TypeScript. We will cover:
- What is a for-each loop?
- Syntax and usage
- How it works under the hood
- Differences from a regular for loop
- When to use for-each
- Advanced examples and use cases
- Best practices
So let‘s get started!
What is a For-Each Loop in TypeScript?
A for-each loop allows you to iterate through an array or other collection data type without needing to manage an index variable and conditionals yourself.
Instead, TypeScript abstracts away these details and gives you access to each element directly on each iteration.
The for-each loop is implemented in TypeScript using the forEach()
method. Most collection data types like arrays have this method available.
Here is the basic syntax:
myArray.forEach(function(value) {
// do something with value
})
This loops through myArray
, assigning the value of each element to value
which you can then access inside the loop body.
The forEach
method handles advancing the index and loop control flow behind the scenes.
This makes your code more readable and abstracts away unnecessary management code needed for a basic for loop.
How Does the For-Each Loop Work?
Under the hood, the forEach()
method iterates through each index of the array or collection data type.
On each iteration, it passes the value into the callback function you provide.
For example:
const numbers = [1, 2, 3];
numbers.forEach(function(num) {
console.log(num);
});
// Prints:
// 1
// 2
// 3
Here the callback is called 3 times, once for each value.
The key things the forEach
handles:
- Initializes index variable
- Increments index each iteration
- Breaks loop when end reached
- Passes current value to callback
This abstracts away a lot of boilerplate code you would need in a regular for loop.
Differences from a Regular For Loop
There are a few key differences between how forEach
and a regular for loop work in TypeScript:
1. No access to index
The for-each callback doesn‘t give you access to the current index. A regular for loop lets you use the index for additional logic:
const numbers = [1, 2, 3];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]); // use index here
}
2. Breaking or continuing
You cannot use break
and continue
statements inside forEach()
.
3. Returns undefined
The for-each loop always returns undefined
. A regular for loop can return a value from inside the loop.
So in cases where you need the index, early termination, or value return – a regular for loop is required.
But in most cases, forEach
provides a cleaner and easier syntax.
When Should You Use For-Each?
Here are the most common cases where a for-each loop shines in TypeScript:
1. Iterating over arrays or lists
Anytime you need to iterate an array/list and work with each value, use forEach
:
const fruits = [‘apple‘, ‘orange‘, ‘banana‘];
fruits.forEach(fruit => {
console.log(fruit);
});
This is more readable than managing the indexes yourself.
2. Transforming array data
Mapping, filtering, reducing – all array operations can be done cleanly with forEach
:
const numbers = [1, 2, 3];
const doubled = [];
numbers.forEach(num => {
doubled.push(num * 2);
});
Here we iterate and transform values into a new array.
3. Object iteration
You can iterate the keys of an object with forEach
as well:
const person = {
firstName: "John",
lastName: "Doe",
age: 32
}
Object.keys(person).forEach(key => {
console.log(key, person[key]);
})
This prints each key/value cleanly.
So in summary, anytime you are working with iterable collections like arrays, use the for-each loop for clean and simple iteration.
Advanced Examples
Let‘s go through some more advanced examples to see the power of forEach()
.
Filtering
We can filter an array to a new array based on a condition:
const numbers = [1, 2, 3, 4];
const evens = [];
numbers.forEach(n => {
if (n % 2 === 0) {
evens.push(n);
}
});
console.log(evens); // [2, 4]
Here we iterate and filter even values into a separate array.
Finding Sum
Calculate the total sum of an array:
const numbers = [1, 2, 3, 4];
let sum = 0;
numbers.forEach(n => {
sum += n;
});
console.log(sum); // 10
Simple sum calculation with for-each.
Map to Object
Convert an array into a lookup object:
const people = [
{ id: 1, name: "John" },
{ id: 2, name: "Sarah" }
];
const lookup = {};
people.forEach(person => {
lookup[person.id] = person;
});
// lookup is now:
// {
// 1: {id: 1, name: "John"},
// 2: {id: 2, name: "Sarah"}
// }
Here each person is mapped to an object for easy lookup via ID.
As you can see, the for-each loop handles these operations cleanly without needing index management.
Best Practices
When using for-each loops in TypeScript, keep these best practices in mind:
Favor immutable data
Avoid mutating the original array or values. For example, instead of:
const names = ["John", "Sarah"];
names.forEach(name => {
name = name.toUppercase(); // mutates
})
Create new data:
const names = ["John", "Sarah"];
const capitalNames = [];
names.forEach(name => {
capitalNames.push(name.toUpperCase());
})
This avoids unintended side effects.
Use arrow functions
Arrow functions provide a concise syntax:
array.forEach(value => {
// do something
})
Return early from loops
If iterating a large array, return early if you no longer need to continue:
numbers.forEach(num => {
if (num > 100) {
return; // no need to keep going
}
})
Handle empty arrays
Always check for empty arrays first to avoid issues:
if (array.length > 0) {
array.forEach(/* ... */)
}
This prevents errors with empty collections.
By following these best practices with for-each loops, you can write clean and robust TypeScript code.
Conclusion
The for-each loop provided by Array.prototype.forEach()
is the easiest way in TypeScript to iterate collections like arrays and lists.
It abstracts away a lot of the verbose boilerplate you would need for a standard for loop with index management.
Use for-each when:
- You need to iterate an array or list
- Transform values by mapping, filtering, finding sums or other operations
- Convert arrays into objects
- Work with keys and values of plain objects
Just be aware of the differences like lack of index or value return compared to regular loops.
By leveraging for-each methods built into TypeScript collections, you can focus on the data and business logic instead ofnanomaterials, nanousources, nanobiology, nanodiagnostics, nanomedicine, nanopores, nanolithography, nanoelectronics and nanocaches.
The development and application of nanotechnology will likely have a profound impact on our economy and society in the early 21st century, comparable to that of semiconductor technology, information technology, or cellular and molecular biology. Science and technology research in nanotechnology promises breakthroughs in areas such as materials and manufacturing, nanoelectronics, medicine and healthcare, energy, biotechnology, information technology and national security. It is widely felt that nanotechnology will be the next Industrial Revolution. US National Nanotechnology Initiative
Here are some key potential benefits of nanotechnology:
- Exceptionally strong and lightweight materials – using nanotubes, nanowires and graphene for building structures, vehicles, spacecraft, etc.
- Higher efficiency solar cells using quantum dots to collect more solar energy. This can help tackle climate change challenges.
- Better diagnostics and targeted drug delivery for disease treatment. Nanoparticles can deliver drugs precisely to tumors and disease sites.
- Rapid whole-genome sequencing – Nanopores can sequence DNA molecules rapidly at low cost. This can enable personalized medicine.
- Higher computing performance – New nanomaterials like graphene, molybdenum disulfide, silicon nanowires used to make smaller, faster and lower power transistors and circuits.
- Higher density storage media – Nanoscale magnetic materials and scanning probes enable high-density data storage for big data applications.
- Better sensors – Nanosensors with higher sensitivity that can detect early disease markers or harmful chemicals in environment or factories.
- Energy storage – Nanostructured electrodes allow Li-ion batteries to charge faster and hold much more energy.
While there has been rapid progress in nanoscience research over the past two decades, nanotechnology is still an emerging field. There are challenges to overcome before many of these exciting applications become commercially viable. But the opportunities ahead are tremendous as nanotech promises to transform medicine, computing, the environment and society as a whole in the decades ahead.