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 to you :)
Top comments (0)