There are different kinds of loops in Javascript. There is the regular for
loop, foreach
loop, for...of
, and for...in
. In this blog post we will take a look at the for...of
and for...in
loops.
for…of
The for...of
loop iterates over objects that are iterable such as arrays, strings and maps.
Structure
for (element of iterableObject) {
...
}
Examples
Arrays
const numbers = [1, 2, 3];
for (const element of numbers) {
console.log(element); //1, 2, 3
}
Maps
const family = new Map([['Father', 'Tom'], ['Mother', 'Anne'], ['Daugher', 'Lisa']]);
for (const element of family) {
console.log(element); //['Father', 'Tom'], ['Mother', 'Anne'], ['Daugher', 'Lisa']
}
OR
for (const [key,value] of family) {
console.log('Key: ' + key); //Father, Mother, Daughter
console.log('Value: ' + value); //Tom, Anne, Lisa
}
Strings
const msg = 'hello';
for (const element of msg) {
console.log(element); //h
//e
//l
//l
//o
}
You can use let
instead of const
if you plan on doing any variable reassigning inside the loop.
for…in
The for...in
loop loops over the properties of an object.
Structure
for (props in object) {
...
}
Example
const userInfo = {id: 100, firstName: 'Jeff', lastName: 'Jorgensen'};
for (const props in userInfo) {
console.log(props); //id
//firstName
//lastName
console.log(userInfo[props]); //100
//Jeff
//Jorgensen
console.log(`${props}: ${userInfo[props]}`); //id: 100
//firstName: Jeff
//lastName: Jorgensen
}
NOTE: Be careful when using a for...in
loop since it does not loop over object properties in order. It should also not be used to loop over arrays where the order of the array index is important.
Modifying properties during iteration should be avoided, except if it is the property that the iterator is currently on. The reason for this, is that one cannot ensure that the iterator will reach a property that will be deleted, for example, before it has been deleted. There is no assurance either, that the iterator will be able to get to a property that has been added to the object or even display the previous or new value for a modified property.