Javascript for…of Loop with example

In this example we will use the for of loop introduces in ES6 to loop through an array as well as the contents within the generator function. In the first example, an array goes into the for of loop and the total of all the elements of that array has been calculated.

let monthlyincome = [1000, 2000, 3000];

let total = 0;

for(let income of monthlyincome)
	total += income
	
console.log(total) // output 6000

Next we continue to loop and add up the contents within the generator function’s income2 by passing income3 into the for of loop.

function* income2() {
	yield 1000; // the yield keyword is needed to return the value.
	yield 3000;
}

function* income3() {
	yield* income2();
}

for(let income of income3())
	total += income
	
console.log(total) // output 10000

Next we add up the array elements within the generator function’s income4() with the for of loop.

 
function* income4() {
	yield* [20000, 30000]
}

for(let income of income4())
	total += income
	
console.log(total) // output 60000

As you can see we can use the for of loop to iterate through the value of an iterable object which makes it a lot more simple than using the next method of the generator function.

Finally we will loop through the elements within an array, add them up and multiply by a factor then return the new value.

let array1 = [1000, 3000]
let array2 = [2000, 5000]
let array3 = [...array1,...array2]
let sum = 0

let total_ = (arry, factor=6) => {
	for(let arr of arry)
		sum += arr
	return factor*(sum)
}

let summation = total_( array3 )

console.log(summation) //66000

Javascript for…of Loop makes thing really simple for the web developer to write a loop since it has been introduced in the ECMAScript6.

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of