In this section, we will learn what the for-in loop is and how to use it in JavaScript.
What is JavaScript for in Loop? (for key in Object JavaScript)
The `for in` statement is used to loop through the properties of an object.
Note: using this statement will return the string representation of name of each property in an object.
for in Loop Syntax:
for (var varName in targetObject){ //body… }
`for`: to create a `for in` statement, we start with the keyword `for`.
`varName`: this is a variable that will hold the name of each property every time the execution engine iterates through the properties of the target object.
`targetObject`: this is the object in which we want to loop through and get all its properties.
`in`: between the `varName` and the `targetObject` we use the `in` keyword to separate them.
`()`: we use the pair of parentheses after the name of the `for` keyword to define the `varName in targetObject` assignment.
`{}`: the body of the `for in` statement starts from the open brace `{` and ends right at the closing brace `}`.
Notes:
- Each time a property name of the `tagetObject` is assigned to the `varName`, the body of the loop will be executed as well.
- The loop will iterate through all the properties of the `targetObject` and return all the names of all the properties.
- After the last property of the `targetObject` the execution engine will end the loop and move towards the instructions after the body of the loop.
Example: loop through object in JavaScript
const person = { firstName: "John", lastName: "Doe", age: 1000 } for (const prop in person){ console.log(typeof prop); console.log(`The name of the property is: ${prop} and its value is: ${person[prop]}`); }
Output:
string The name of the property is: firstName and its value is: John string The name of the property is: lastName and its value is: Doe string The name of the property is: age and its value is: 1000
Example: using break statement in for in loop
const person = { firstName: "John", lastName: "Doe", age: 1000 } for (const prop in person){ if (prop =="lastName"){ break; } console.log(prop); }
Output:
firstName
Example: using continue statement in for in loop
const person = { firstName: "John", lastName: "Doe", age: 1000 } for (const prop in person){ if (prop =="firstName"){ continue; } console.log(prop); }
Output:
lastName age