Using For-In Loop to coding in Javascript/JS

This JavaScript tutorial explains how to use the for-in loop with syntax and examples.

Description

In JavaScript, the for-in loop is a primary manage announcement that lets in you to loop thru the properties of an object. The statements of code found inside the loop body will be achieved once for every property of the object.

Syntax

The syntax for the for-in loop in JavaScript is:

for (variable in object) {
   // statements
}

Parameters or Arguments

variable The name of a variable, an thing of an array, or the property of an object. object A legitimate object or title of an object whose houses will be iterated through. statements The statements of code to execute every pass by through the loop.

Note

The physique of the for-in loop will execute once for each property of the object. The for-in loop does no longer loop via all of the houses of the object. It is can solely loop thru the enumerable houses such as user-defined properties or inherited user-defined properties. Any properties that are flagged as non-enumerable (such as built-in houses or methods) will now not be iterated through the use of the for-in loop. Since there is no precise order that the object homes are enumerated in the for-in loop, JavaScript may iterate through the houses in a specific order depending on your implementation or version of JavaScript. See also the smash declaration to exit from the for-in loop early.

Example

Let’s seem to be at an instance that indicates how to use a for-in loop in JavaScript.

For example:

var totn_colors = { primary: 'blue', secondary: 'gray', tertiary: 'white' };

for (var color in totn_colors) {
   console.log(totn_colors[color]);
}

In this example, the following will be output to the net browser console log:

blue
gray
white

TIP: Each implementation of JavaScript might also iterate through the residences in a unique order. The above output is what appears in our implementation of JavaScript, however the output may show up in a special order in your model of JavaScript.

Using the for-in loop with an Array

Since an array is an object, you can use the for-in loop to iterate thru the elements of the array.

The following is the equal example as above, but the use of an array:

var totn_colors = [ 'blue', 'gray', 'white' ];

for (var color in totn_colors) {
   console.log(totn_colors[color]);
}

In this example, the following will be output to the web browser console log:

blue
gray
white