Friday , 17 November 2017
Home / Programming / JavaScript / For In Loop – JavaScript Tutorial
For In Loop
For In Loop

For In Loop – JavaScript Tutorial

This tutorial is part of the JavaScript tutorial series for beginners. To view the whole list of tutorials available and the order in which you should follow them, then click here.

The for in loop in JavaScript is a special kind of loop. It’s specifically designed for arrays and objects. It allows you to loop through an array or object’s elements or properties. Let’s take a look at how to do this.

Clear your script and add this bit of code.

You create an array. Next, we create our for in loop. Inside the parenthesis, you define the variable that will represent each element in the array. Each time this loop runs, this variable will represent the current element the loop is in. The in keyword tells JavaScript what Array to use and then it’s followed by the name of the array itself.

The variable does not represent the value, but the index. So, inside our loop, we’re using x as the index and not outputting it out itself. If we did, you would just get a bunch of numbers. You should get the following outputted.

James
Bob
Billy

Let’s take a look at how to use the for in loop with objects. Clear your script and add this bit of code.

First, we create a class and inside this class are a couple of properties. Then, we create an instance. Lastly, we use the for in loop to loop through the object. Like last time, y represents the name of the property. It does not represent the value.

If you refresh your document, then you should get something like this.

red
blue
green

Conclusion

The for in loop is very confusing. The only way to really get it in your head is to practice using it. If you would like more information about the for in loop, then go here.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for…in

About Jasko Koyn

Check Also

Try-Catch Statement

Try-catch Statement – Advanced JavaScript Tutorial

The try-catch statement is a unique way to handle errors. When errors occur, usually it …

Leave a Reply

Your email address will not be published. Required fields are marked *

ULTIMATE WORDPRESS DEVELOPMENT COURSE
Want to learn how to create your own custom WordPress plugins and themes? Check out my course!
Get 93% off my course. You'll also learn how to integrate WooCommerce and BuddyPress into your projects. This is a limited time offer
Yes, I would like to get 93% off your course!
No Thanks!
close-link