In JavaScript, the for...in
loop is used to iterate over the properties of an object. It iterates through all enumerable properties of an object, including properties inherited from its prototype chain. Here's the basic syntax of the for...in
loop:
for (variable in object) { // code to be executed }
variable
: A variable that represents the property name. It is assigned the property name on each iteration.object
: The object whose enumerable properties are to be iterated over.Here's an example of using the for...in
loop to iterate over the properties of an object:
const person = { name: "John", age: 30, profession: "Developer" }; for (let key in person) { console.log(key + ": " + person[key]); }
In this example:
key
represents the property name of the person
object.person[key]
retrieves the value associated with the current property name (key
).The loop will iterate over each enumerable property of the person
object and print both the property name and its corresponding value.
However, it's important to note that the for...in
loop should not be used to iterate over arrays due to its behavior with array-like objects and potential issues with iterating over non-enumerable properties or inherited properties. Instead, for arrays, you should typically use a for
loop or Array.forEach()
method.