for...in and for...of
You can use the for...in
and for...of
statements to work with loops.
for...in
The for...in
loop iterates over all enumerable properties of an object.
Basic structure of for...in loop
for (variable in object) {
// code to be executed
}
For example, you can iterate over the properties within an object as follows:
Example usage of for...in loop
const student = {
name: 'CodeFriends',
age: 20,
};
for (let key in student) {
console.log(key, ':', student[key]);
}
The code above will output the following:
Example output
name: CodeFriends
age: 20
for...of
The for...of
loop is used to iterate over values of iterable objects (e.g., Arrays, Strings, Sets, Maps, etc.).
Using for...of
, you can retrieve each item in an array one by one.
Basic structure of for...of loop
for (variable of iterable) {
// code block
}
Example of looping through an array
const fruits = ['Apple', 'Banana', 'Grapes'];
for (let fruit of fruits) {
console.log(fruit);
}
This code will output:
Output of the array example
Apple
Banana
Grapes
You can also use for...of
with strings, as shown below:
Example of looping through a string
const serviceName = 'CodeFriends';
for (let char of serviceName) {
console.log(char);
}
This code will output:
Output of the string example
C
o
d
e
F
r
i
e
n
d
s
In summary, for...in
iterates over object properties, whereas for...of
iterates over values of iterable objects.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.