For Loops in JavaScript
JavaScript has at least three distinct ways of defining "for" loops:
for
: Runs a block of code a number of times;for/in
: Iterates over properties of a given object;for/of
: Iterates over the values of iterable objects;
For
This loop repeats the execution of your block of code until a specified condition becomes false.
Let's check the syntax of this simpler loop:
for (statement 1; statement 2; statement 3) {
// block of code to be executed
}
Statement 1 is executed only once before your block of code runs. Usually we define the loop's initial condition, but this is an optional parameter and can be defined before the loop statement if needed.
Statement 2 defines the condition for the execution of the code block. Here you end up defining how many times the code block will run. This parameter is also optional, though if omitted, it's necessary to add a break inside your code block, otherwise the loop will never finish and the browser will crash.
Statement 3 is executed once for each execution after your code block runs. As you might have guessed by now, this parameter is also optional.
const languages = [âjavascriptâ, âpythonâ, âphpâ];
for (let i = 0; i < languages.length; i++) {
console.log(`${i}: ${languages[i]}`)
}
// expected output:
// â0: javascriptâ
// â1: pythonâ
// â2: phpâ
For/in
This loop iterates over an object's properties (keys).
const js = { name: âJavaScriptâ, author: âBrendan Eichâ, year: 1995 };
for (const prop in js) {
console.log(`${prop}: ${js[prop]}`);
}
// expected output:
// âname: JavaScriptâ
// âauthor: BrendanEichâ
// âyear: 1995â
The same could be done using a simple "for" loop using Object.keys
, which extracts the properties of an object to an array:
const js = { name: âJavaScriptâ, author: âBrendan Eichâ, year: 1995 };
const properties = Object.keys(js);
for (i = 0; i < properties.length; i++) {
const prop = properties[i]
console.log(`${i} ${prop}: ${js[prop]}`);
}
// expected output:
// â0 name: JavaScriptâ
// â1 author: Brendan Eichâ
// â2 year: 1995â
For/of
This runs the loop over the values of iterable objects. A few examples of iterable objects in JS are Arrays, Strings, Maps, Sets and NodeLists. The syntax is as follows:
for (*variable* of *iterable object*) {
// code block to be executed
}
Here's an example like the previous:
const languages = [{ name: âJavaScriptâ }, { name: âPythonâ }, { name: âPHPâ }];
for (const lang of languages) {
console.log(lang);
}
// expected output:
// { name: âJavaScriptâ }
// { name: âPythonâ }
// { name: âPHPâ }
Both for/in
and for/of
are very useful, each being used in their own way can make your code more legible, in my opinion. Hopefully this tip has been useful for you :)