Syntax
JS
for
, while
, and do-while
statements.// for loopfor (initialization; condition; iteration) { // code to execute in each iteration }// while loopwhile (condition) { // code to execute while the condition is true }// do-while loopdo { // code to execute at least once, then continues while the condition is true } while (condition);
Python
for
and while
statements.# for loop for variable in sequence: # code to execute in each iteration # while loop while condition: # code to execute while the condition is true
Javascript | Python |
---|---|
Syntax | |
// for loop for (initialization; condition; iteration) { // code to execute in each iteration } // while loop while (condition) { // code to execute while the condition is true } // do-while loop do { // code to execute at least once, then continues while the condition is true } while (condition); |
# for loop for variable in sequence: # code to execute in each iteration # while loop while condition: # code to execute while the condition is true
|
Range-based For Loop | |
|
for i in range(start, end): # code to execute for each iteration |
Loop Control Statements | |
// break statement for (let i = 0; i < 10; i++) { if (i === 5) { break; // exit the loop when i equals 5 } } // continue statement for (let i = 0; i < 10; i++) { if (i === 5) { continue; // skip the current iteration when i equals 5 } } |
# break statement for i in range(10): if i == 5: break # exit the loop when i equals 5 # continue statement for i in range(10): if i == 5: continue # skip the current iteration when i equals 5
|
For...in Loop | |
for (let key in object) { if (object.hasOwnProperty(key)) { // code to be executed } }
for (let element of array) { // code to be executed } |
for item in my_list: # code to execute for each item |
Iteration over Arrays and Collections | |
// for loop for (let i = 0; i < array.length; i++) { // access array elements using array[i] } // forEach() array.forEach(function(element) { // code to execute for each element }); |
# for loop for element in array: # access array elements using element |
Iteration over Objects and Dictionaries | |
// for...in loop for (let key in object) { // access object properties using object[key] } // Object.keys() Object.keys(object).forEach(function(key) { // access object properties using object[key] }); |
# for loop for key, value in dictionary.items(): # access dictionary keys using key # access dictionary values using value |
Nesting Loops | |
|
|
Infinite Loops | |
| In Python, you can create an infinite loop using while True and break out of the loop using a conditional if statement with break . |