Python.v.JavaScript

JavaScript for Pythonistas. Python for JavaScripters

For loop

for loop is used mostly for two goals:

  1. Do something given number of times.
  2. Process all elements of some data structure (e.g. list).
Python Javascript
Do the loop given number of times #
for i in range(4):
    print("i =", i)
i = 0
i = 1
i = 2
i = 3
for(var i=0; i<4; i++) {
    console.log("i =", i);
}
i = 0
i = 1
i = 2
i = 3
Process all elements of list / array #
my_list = [1, 2, 10]
for element in my_list:
    print(element)
1
2
10
var my_array = [1, 2, 10];
for (var i=0; i<my_array.length; i++) {
    console.log(my_array[i])
}
1
2
10

This is the most safe way to process all elements of array. Supported in all versions of JS, there is no possibility to mistakenly include properties that are not indexed elements of a list, see another example.


var my_array = [1, 2, 10];
for (i in my_array) {
    console.log(my_array[i]);
}
1
2
10

var my_array = [1, 2, 10];
for (element of my_array) {
    console.log(element)
}
1
2
10
require: es6
var my_array = [1, 2, 10];
my_array.forEach(function(v) {
    console.log(v)
})
1
2
10
Value of loop variable after exit #
for i in range(4):
    print("Step", i)
print("Outside of loop, i =", i)
Step 0
Step 1
Step 2
Step 3
Outside of loop, i = 3
for (var i=0; i<4; i++) {
   console.log("Step", i)
}
console.log("Outside of loop, i =", i)
Step 0
Step 1
Step 2
Step 3
Outside of loop, i = 4

for (let i=0; i<4; i++) {
   console.log("Step", i)
}
console.log("Outside of loop, i =", i)
Step 0
Step 1
Step 2
Step 3
[stdin]:4
console.log("Outside of loop, i =", i)
                                    ^

ReferenceError: i is not defined
    at [stdin]:4:37
    at Script.runInThisContext (vm.js:132:18)
    at Object.runInThisContext (vm.js:315:38)
    at Object.<anonymous> ([stdin]-wrapper:10:26)
    at Module._compile (internal/modules/cjs/loader.js:1256:30)
    at evalScript (internal/process/execution.js:98:25)
    at internal/main/eval_stdin.js:29:5
    at Socket.<anonymous> (internal/process/execution.js:211:5)
    at Socket.emit (events.js:326:22)
    at endReadableNT (_stream_readable.js:1244:12)
require: es6
Caveats of list elements enumeration with in #
my_list = [1, 2, 10]
my_list.some_value = "I'm here!"
for element in my_list:
    print(element)
Exception: AttributeError
'list' object has no attribute 'some_value'

It is impossible to add properties to instance of standard list class.


class MyList(list):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
brand_new_list = MyList([1, 2, 10])
brand_new_list.some_value = "I'm here!"
for element in brand_new_list:
    print(element)
1
2
10

It is possible to inherit from list (although not recommended) and add additional properties to an instance of this new class. It does not affect enumerating with for ... in ....

var my_array = [1, 2, 10];
my_array.some_value = "I'm here!";
for (i in my_array) {
    console.log(my_array[i]);
}
1
2
10
I'm here!

In JavaScript, Array is just an (optimized) Object with numeric indexes. If you add some properties (with string index) into this object, this property will be enumerated with for ... in ....


var my_array = [1, 2, 10];
Array.prototype.some_value = "I'm here!";
for (i in my_array) {
    console.log(my_array[i]);
}
1
2
10
I'm here!
Enumeration of keys in dictionary / object #
my_dict = {'a': 10, 'b': 20}
for key in my_dict:
    print(key)
a
b
my_obj = {a: 10, b: 20}
Object.prototype.new_property = function() {
    return "Hello";
}
for (key in my_obj) {
    console.log(key);
}
a
b
new_property

In JavaScript objects, there's no difference between key-value records, properties and methods. Moreover, not only elements of object are enumerated, but also elements of a prototype (if they are not marked with enumerable: false).


my_obj = {a: 10, b: 20}
Object.prototype.new_property = function() {
    return "Hello";
}
for (key in my_obj) {
    if (my_obj.hasOwnProperty(key)) {
        console.log(key);
    }
}
a
b
Enumeration of keys and values in dictionary / object #
my_dict = {'a': 10, 'b': 20}
for key, value in my_dict.items():
    print(key, "=>", value)
a => 10
b => 20
my_obj = {a: 10, b: 20}
Object.prototype.new_property = function() {
    return "Hello";
}
for (key in my_obj) {
    if (my_obj.hasOwnProperty(key)) {
        console.log(key, "=>", my_obj[key]);
    }
}
a => 10
b => 20
reference

See comment to other example.

© Ilya V. Schurov and contributors, 2017
Licenses: CC BY (text), MIT (code).
contribute on github