If you are a Javascript developer, you know, there are different kinds of loops you can use in JS.
Background Image Credit: Giphy
For example, there are 3 types of for loops -
- Basic For Loop
- For...of Loop
- For...in Loop
Every for loop iterates through the elements. The difference is how you use them and what they returns
Let's have a brief look inside! 😉
🅰️ For...of
const fruits = ["Mango", "Berry", "Orange"]
let text = "";
for (let fruit of fruits) {
text += fruits
}console.log(text)//It is now "MangoBerryOrrange"
const text = 'foo'for (const char of text)console.log(text)// "f"// "o"// "o"
- When you just care about the value, not about their position. For example, when testing elements in array
- When you want to add up or replace specific content in list
- Not the best way, but you can search contents in a list using this loop
- Remember, for...of loop is specially useful for Arrays not Objects
🅱️ For...in
var obj = {a: 1, b: 2, c: 3}for (const prop in obj) {console.log(`${prop} = ${obj[prop]}`)}// "a = 1"// "b = 2"// "c = 3"
A for...in
loop only iterates over enumerable, non-Symbol properties
It's not really recommended to use for...in with Arrays or Strings as for...of loop works really good there. But for...in loop is very important when you store data in Objects.
👉 For example, we need to display posts from data retrieved from database. It's usually in an array.
So, first you run a for...of loop to get each individual element of the list(Array). Then, every post data is obviously stored in an Object. So, you can run a for...in loop to get all those data and do something.
🥳 Ta da!
There are other cases when you will need for...in loop. Let's summarize it -
When do you use for...in?
- To work with data stored in Object
- To test and process data based on key
- To debug your code
Comments
Post a Comment