Iterate elements of an array in Python and Javascript

We are going to make a comparison among two ways to iterate through elements in Python and Javascript.

Iterate in Python

Python has the most clean code to iterate through element of an array (a list, in Python’s language).

a = [1,2,3]

for element in a:
    print(element)

Output:

1
2
3
>>>

Iterate in javascript

Javascript has the forEach method to iterate the elements.

a.forEach(function(element){
   console.log(element); 
});
1
2
3

Iterate in javascript (arrow function)

You can also use the arrow function like this (it’s the same thing as above):

a.forEach(element => {
  console.log(element);  
});
1
2
3

 

Even more similar

You can also go in a loop in something more close to Python’s language in javascript.

Getting the index out of it

When you use in in the for loop, you will have the index number of each element.

let arr = [1,2,3];

for (let index in arr){
 console.log(index)
}

This will just give you the index of the element, not the element itself.

Output:

0
1
2

Getting the item out of an array with ‘in’

If you want the element with the ‘in’, you can look into the arr[index] to get the element.

let arr = [1,2,3];

for (let index in arr){
 console.log(arr[index])
}

Output

1
2
3

Getting the item directly with ‘of’

Using ‘of’, you got the element without having to use the index.

let arr = [1,2,3];

for (let item of arr){
 console.log(item)
}

Output

1
2
3

The classic for loop

Finally we have the classic way to make a loop through the items of an array in javascript, that is more complex to write, compared to the other ways.

for (i=0; i<a.length; i++){
    console.log(a[i])}

Output

1
2
3


Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.