for...in and for...of
You can utilize loops using the for...in
and for...of
syntax.
for...in
The for...in
loop iterates over all enumerable properties of an object.
for (variable in object) { // Execute code }
For example, you can iterate over an object's properties like this:
const student = { name: 'CodeBuddy', age: 20, }; for (let key in student) { console.log(key, ':', student[key]); }
The code above will output the following:
name: CodeBuddy; age: 20;
for...of
The for...of
loop is used to loop over values from iterable objects (e.g., arrays, strings, Sets, Maps, etc.).
Using for...of
, you can iterate through each item in an array.
for (variable of iterable) { // Code block }
const fruits = ['Apple', 'Banana', 'Grape']; for (let fruit of fruits) { console.log(fruit); }
This code will result in the following output:
Apple Banana Grape
Similarly, you can use for...of
with strings as shown below:
const serviceName = 'CodeBuddy'; for (let char of serviceName) { console.log(char); }
This will output the following:
C o d e B u d d y
To summarize, for...in
iterates over an object's properties, while for...of
retrieves and iterates through values of an iterable object in order.
The for...of loop is used to iterate over an object's properties.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result