Javascript’s for…in loop iterates through each property of the object.
Syntax
The syntax of the for…in loop is as follows:
// body of the for...in loop
}
where,
The key is the variable used in each iteration.
The object is the required object from which to iterate the loop.
Next, we will go over some examples to reinforce the concept and show you how the process works.
Examples
First, we see the simplest implementation of the for…in loop. In this example, we will first assume an object:
firstName: "John",
lastName: "Doe"
}
And then, we will iterate through the object and console each property using the for…in loop.
console.log(name + " = " + obj[name]);
}
As you can see, the for…in loop has iterated through each property of the obj object and printed each property in the console, as we desired.
Javascript also provides the built-in hasOwnProperty() function. We can perform the hasOwnProperty() check before performing any task in the for…in loop, like this:
if (obj.hasOwnProperty(name)) {
console.log(name + " = " + obj[name]);
}
}
This function comes in handy when you need to use JSON or for debugging purposes.
When you do not know whether the key holds certain properties, you can also use the for…in syntax for the arrays, as well as for the strings.
for (const value in arr) {
console.log(value + " = " + arr[value]);
}
Similarly, you can apply this syntax to the strings, as well.
for (const char in str) {
console.log(char + " = " + str[char]);
}
But, it is not recommended to use the for…in loop for arrays and strings because there are dedicated loops and functions for arrays and strings. Like, for…of or Array.protptype.forEach() is for the arrays for doing the same tasks in better ways.
Conclusion
In this article, you learned how the for…in loop works and how it helps with JSON and debugging. You also learned how to use the for…in loop with arrays and strings, although this loop is dedicated to and recommended for objects. But, I hope this article proved helpful to your understanding of the for…in loop and its various implementations. To learn more about Javascript, you can find more articles at linuxhint.com.
from Linux Hint https://ift.tt/2HiTkfM
0 Comments