JavaScript loop

The JavaScript loop iterates over the properties of an object.

Here's a simple example of the loop in JavaScript. Read the rest of the tutorial to learn more.


const student = {
    name: "Monica",
    class: 7
// loop through student properties for (let key in student) { // display the properties console.log(`${key} => ${student[key]}`); };
// Output: // name => Monica // class => 7

Here, the key of each property of the student object is stored in the key variable. We then used student[key] to access the corresponding value.

Syntax of JavaScript loop

The syntax of the loop is:

for (key in object) {
    // body of

The loop iterates over all object properties. In each iteration of the loop, the key variable is assigned the name of an object property.

Notes: Once you get the keys of an object, you can easily find their corresponding values.

Example: JavaScript Loop

const salaries = {
    Jack : 24000,
    Paul : 34000,
    Monica : 55000

// use to loop through // properties of salaries for (let i in salaries) { // access object key using [ ] // add a $ symbol before the key let salary = "$" + salaries[i]; // display the values console.log(`${i} : ${salary}`); };


Jack : $24000,
Paul : $34000,
Monica : $55000

In the above example, we used the loop to iterate over the properties of the salaries object. Then, we added the string $ to each value of the object.

Note: We have used the variable i instead of key because we can use any valid variable name.

More on JavaScript Loop

JavaScript With Strings

You can also use the loop to iterate over string values. For example,

const string = 'code';

// using loop
for (let i in string) {


JavaScript With Arrays

You can also use with arrays. For example,

// define array
const arr = ["hello", 1, "JavaScript"];

// using loop
for (let x in arr) {



Note: You should not use to iterate over an array where the index order is important. Instead, it's better to use the for...of loop.

Also Read:

Did you find this article helpful?