JavaScript loop

In this tutorial, you will learn about the JavaScript loop with the help of examples.

In the previous tutorials, we have covered:

There are also other types of loops. The loop in JavaScript allows you to iterate over all property keys of an object.

JavaScript loop

The syntax of the loop is:

for (key in object) {
    // body of

In each iteration of the loop, a key is assigned to the key variable. The loop continues for all object properties.

Note: Once you get keys, you can easily find its value.

Example 1: Iterate Through an Object

const student = {
    name: 'Monica',
    class: 7,
    age: 12

// using
for ( let key in student ) {

    // display the properties
    console.log(`${key} => ${student[key]}`);


name => Monica
class => 7
age => 12

In the above program, the loop is used to iterate over the student object and print all its properties.

  • The object key is assigned to the variable key.
  • student[key] is used to access the value of key.

Example 2: Update Values of Properties

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

// using
for ( let i in salaries) {

    // add a currency symbol
    let salary = "$" + salaries[i];

    // display the values
    console.log(`${i} : ${salary}`);


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

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

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

const string = 'code';

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


e with Arrays

You can also use with arrays. For example,

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

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



You will learn more about the arrays in later tutorials.

Note: You should not use to iterate over an array where the index order is important.

One of the better ways to iterate over an array is using the for...of loop.

To learn more about the for...of loop, visit JavaScript for...of loop.