You are here: Home / Topics / How to Iterate an array elements using For Loop in JavaScript

How to Iterate an array elements using For Loop in JavaScript

Filed under: JavaScript on 2023-08-06 23:04:29

In this post, you will see how you can iterate elements of an array in javascript.

Note: here we have an array of numbers.

We can find the number of elements in this array by using array.length i.e 6. 

Now we will run for loop six times to print all the elements.

All of you know that array starts with 0 index. So if you initialize i with 0 then you have run loop until i ≤ (array.length-1) because we are starting from 0. Let's dive in the code now.

Code

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Iterate Array Using For Loop</title>
</head>
<body>
   <script>
       var array = [10, 20, 30, 40, 50, 60];
       for(let i = 0; i<= (array.length-1); i++){
           console.log(array[i]);
       }
   </script>
</body>
</html>

 

Output of this code will be;

10
20
30
40
50
60

If you run for loop for more that array.length it will give you undefined value.

About Author:
M
Mr. Dubey     View Profile
Founder and CEO of MCQ Buddy. I just like to help others. This portal helps students in getting study material free.