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 :)