Skip to content

Loops (iteration)

This article uses Office Scripts to explain how to implement loops, with sample code.

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.

Sample using for...of
const fruits = ['Apple', 'Orange', 'Banana'];
// Loop through each element
for (const one of fruits) {
console.log(one);
}
Output
Apple
Orange
Banana

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.

Sample using for...in
const sports = ['Soccer', 'Baseball', 'Basketball'];
// Loop using the index
for (const i in sports) {
console.log(sports[i]);
}
Output
Soccer
Baseball
Basketball

Finally, here’s a loop that uses the ordinary for statement, which is also common in other languages.

Sample using for
const fruits = ['Apple', 'Orange', 'Banana'];
// Loop using the length of the array
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output
Apple
Orange
Banana

To skip ahead to the next iteration while a for statement is running, use continue.

To exit a for loop, use break.

continue and 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]);
}
Output
Skipped
Skipped
Basketball
Table tennis

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.

Sample using forEach
const fruits = ['Apple', 'Orange', 'Banana'];
// Loop through each element
fruits.forEach((fruit, i) => {
console.log(`Fruit #${i + 1} is ${fruit}`);
});
Output
Fruit #1 is Apple
Fruit #2 is Orange
Fruit #3 is Banana

The 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.

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.

Sample using while
let count = 0;
while (count < 1000) {
count++;
}
console.log(count);
Output
1000