Loops (iteration)
This article uses Office Scripts to explain how to implement loops, with sample code.
for statements
Section titled “for statements”Loops with for-of statements
Section titled “Loops with for-of statements”To run code for each element of an iterable object, use the for...of statement.
You get each element of the array as a variable.
const fruits = ['Apple', 'Orange', 'Banana'];
// Loop through each elementfor (const one of fruits) { console.log(one);}AppleOrangeBananaLoops with for-in statements
Section titled “Loops with for-in statements”Next is a loop that uses the for...in statement.
Unlike for...of, it gives you the index (the object’s property name) as a variable instead of the element.
const sports = ['Soccer', 'Baseball', 'Basketball'];
// Loop using the indexfor (const i in sports) { console.log(sports[i]);}SoccerBaseballBasketballLoops with ordinary for statements
Section titled “Loops with ordinary for statements”Finally, here’s a loop that uses the ordinary for statement, which is also common in other languages.
const fruits = ['Apple', 'Orange', 'Banana'];
// Loop using the length of the arrayfor (let i = 0; i < fruits.length; i++) { console.log(fruits[i]);}AppleOrangeBananacontinue and break
Section titled “continue and break”To skip ahead to the next iteration while a for statement is running, use continue.
To exit a for loop, use break.
const sports = ['Baseball', 'Soccer', 'Basketball', 'Table tennis', 'Volleyball'];
for (let i = 0; i < sports.length; i++) { if (i < 2) { console.log('Skipped'); continue; } if (i > 3) { break; } console.log(sports[i]);}SkippedSkippedBasketballTable tennisThe forEach method
Section titled “The forEach method”Arrays (Array) have a forEach method.
You can use forEach to run code for each element. The callback function receives the element as its first argument and the index as its second argument.
In Office Scripts, you can use only arrow functions (() => {}) as callback functions passed to array methods.
const fruits = ['Apple', 'Orange', 'Banana'];
// Loop through each elementfruits.forEach((fruit, i) => { console.log(`Fruit #${i + 1} is ${fruit}`);});Fruit #1 is AppleFruit #2 is OrangeFruit #3 is BananaThe second argument of the callback function is optional.
Note that you can’t use break or continue inside forEach. If you want to exit the loop partway through, use for...of or an ordinary for statement.
while statements
Section titled “while statements”Here’s how to implement a loop with the while statement.
for statements are often used with iterable objects such as arrays, whereas while statements are suited to repeating a loop for as long as a condition is met. They’re handy when you don’t know in advance how many times the loop will repeat.
let count = 0;while (count < 1000) { count++;}console.log(count);1000