for
loop is used mostly for two goals:
Python | Javascript |
---|---|
Do the loop given number of times # | |
i = 0 i = 1 i = 2 i = 3 |
i = 0 i = 1 i = 2 i = 3 |
Process all elements of list / array # | |
1 2 10 |
1 2 10
1 2 10
1 2 10require: es6
1 2 10 |
Value of loop variable after exit # | |
Step 0 Step 1 Step 2 Step 3 Outside of loop, i = 3 |
Step 0 Step 1 Step 2 Step 3 Outside of loop, i = 4
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 # | |
Exception: AttributeError 'list' object has no attribute 'some_value' It is impossible to add properties to instance of standard
1 2 10 It is possible to inherit from |
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
1 2 10 I'm here! |
Enumeration of keys in dictionary / object # | |
a b |
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
a b |
Enumeration of keys and values in dictionary / object # | |
a => 10 b => 20 |
a => 10 b => 20reference See comment to other example. |
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.