loading...

Discussion on: Python for JavaScript Developers

bmarkovic profile image
Bojan Markovic

You're right.

for .. in iterates over key, i.e. it's comparable to something like:

for (let i = 0, o = Object.keys(X); i < o.length; i++, x=o[i]) { .. }

whereas for .. of iterates over iterables i.e. it's roughly comparable to something like:

for (let x, o; o && o.done === false; o = X.next(), x = o && o.value) { .. }

It's slightly more complicated than that because it implicitly converts some objects, such as Arrays or Maps, to iterables.

JavaScript since ES6 also has generators and iterators that work somewhat similar. There are no exceptions, tho, because iterator interface (that generators also need to adher to in general) returns an object on calls to .next() that is of form {done, value}. When done is false you've reached the end of the iterable.

Thread Thread
cben profile image
Beni Cherniavsky-Paskin

But note that in python for key in {1: 10, 2: 20}: iterates over dictionary's keys.

You can use for value in d.keys():, for (key, value) in d.items(): and (redundant) for k in d.keys():.
These methods exist in both Python 2 and 3, though with some differences (see python.org/dev/peps/pep-3106/).

Thread Thread
tomleo profile image
Tom Leo

You can drop the parenthesis i.e. for k, v in thing.items(). You only need parenthesis for comprehension i.e. {k: v for (k,v) in thing.items()} or [(k,v) for (k,v) in thing.items()]