Skip to content
the poor coder

for in loop in javascript

Poor Man
Published
Reading time
2 min read
On this page

For In Loop in JavaScript#

For in loop is used in JavaScript to iterate over the properties of an object. It is a convenient way to loop through the properties of an object without having to know the exact number of properties beforehand. The basic syntax for the for in loop is as follows:

Text
for (var property in object) {
  // code to be executed
}

The above code will iterate over all the properties of the object and execute the code block for each property. The variable "property" will hold the name of the property on each iteration.

Example#

Let's take an example to understand it better:

Text
<div id="output"></div>

<script>
var person = {firstName:"John", lastName:"Doe", age:25};

for (var prop in person) {
  document.querySelector("#output").innerHTML += prop + ": " + person[prop] + "<br>";
}
</script>

In the above example, we have an object "person" with three properties. We are using a for in loop to iterate over all the properties of the object and print them to the HTML page. The output will be:

  • firstName: John
  • lastName: Doe
  • age: 25

Multiple Ways to Use For In Loop#

There are multiple ways to use the for in loop in JavaScript:

  • Iterating over object properties: This is the most common use case for the for in loop, as shown in the example above.
  • Iterating over array elements: The for in loop can also be used to iterate over the elements of an array, but it is not recommended as it can have unexpected results. The recommended way to iterate over array elements is to use a for loop or the forEach method.
  • Iterating over string characters: The for in loop can also be used to iterate over the characters of a string.

Conclusion#

The for in loop is a powerful feature of JavaScript that allows you to iterate over the properties of an object. However, it is important to use it carefully and understand its limitations to avoid unexpected results. It is a great tool to have in your JavaScript toolkit and can be used in many different scenarios.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC