You must know about For loop, while loop, do while loop, etc. But do you know about the For in loop? Why should we use it when we have already for loop ? If you don't know, then just spend your precious 5-10 minutes here and make a step towards becoming master in JavaScript. Let's start it :
For in loop is almost similar to For loop but with shorter syntax. As always, we'll understand its definition :
Loop through the elements in an array or the properties of an object less syntax to write, but less flexible.
Let's understand it with the simplest example :
I have an array of my favorite sports and I want to access its elements. How can I access it ?
Using For Loop :
const favSports = ["Cricket", "Football", "Tennis","Baseball"];
for (let i = 0; i < favSports.length; i++)
{
console.log(favSports[i]);
}
// Cricket
// Football
// Tennis
// Baseball
We have accessed all the elements of our array using For loop.
But the same output we can also acheived using For in loop.
Using For in Loop :
const favSports = ["Cricket", "Football", "Tennis","Baseball"];
for (var element in favSports)
{
console.log(favSports[element])
}
// Cricket
// Football
// Tennis
// Baseball
Have you noticed its syntax ? Doesn't it look shorter and more clear than For loop ? This is the major advantage of For in loop.
The only disadvantage with for in is that we can't increment or decrement our loop as per our wish.
Can we access the properties of Object too using For in ?
The answer is YES. But before let's see earlier how we would access the property of Object :
const myObj = {
name : "Ravi",
age : "27",
country : "India"
}
console.log(myObj.name) // Ravi
console.log(myObj.age) // 27
console.log(myObj.country) // India
We need to write every time the name of Object which is myObj to access the property. It's look good because we have mentioned only three properties but what if we have more than 100+ ?
The solution is again For in loop. Let's see how :
const myObj = {
name : "Ravi",
age : 27,
country : "India"
}
for(var property in myObj)
{
console.log(myObj[property])
}
// Ravi
// 27
// India
With just one line of code, we access the all property of our Object which is myObj
This is how we learned about For in loop.
If you really love ❤️ this article, please hit a like ✅ or drop a comment. I'll keep posting the articles related to JavaScript and Front End development.