Simple For Loop in Swift, Kotlin and JavaScript
A core feature of all programming languages is the trusty for
loop. For loops execute a statement a predefined number of times with some way to exit the loop early.
Swift
Swift uses range operators to construct simple for loops.
1let start = 0
2let end = 10
3
4for i in start ... end {
5 print(i) // prints 0 through 10
6}
7
8for i in start ..< end {
9 print(i) // prints 0 through 9
10}
To increment the counter other than by 1, Swift has a stride keyword.
1let start = 0
2let end = 10
3
4for i in stride(from: start, to: end, by: 2) {
5 print(i) // prints 0, 2, 4, 6, 8 (10 is not included)
6}
7
8for i in stride(from: end, to: start, by: -2) {
9 print(i) // prints 10, 8, 6, 4, 2 (0 is not included)
10}
To break out of a for loop early, Swift uses the break
keyword.
1let start = 0
2let end = 10
3
4for i in start...end {
5 if i > 4 {
6 break
7 }
8 print(i) // prints 0, 1, 2, 3, 4
9}
Kotlin
Kotlin uses a similar range operator for the inclusive range, and the until
keyword for a non-inclusive range.
1val start = 0
2val end = 10
3
4for (i in start..end) {
5 print(i) // prints 0 through 10
6}
7for (i in start until end) {
8 print(i) // prints 0 through 9
9}
To increment the counter by other than 1, Kotlin uses the step
keyword.
1val start = 0
2val end = 10
3
4for (i in end downTo start step 2) {
5 print(i) // prints 10, 8, 6, 4, 2, 0
6}
7
8for (i in start..end step 2) {
9 print(i) // prints 0, 2, 4, 6, 8, 10
10}
To break out of a for
loop early, Kotlin uses the break
keyword.
1val start = 0
2val end = 10
3
4for (i in start..end) {
5 if (i > 4) break
6 print(i) // prints 0, 1, 2, 3, 4
7}
JavaScript
JavaScript follows the traditional C/C++ for loop syntax.
1const start = 0
2const end = 10
3
4for (let i = start; i <= end; i++) {
5 console.log(i) // prints 0 through 10
6}
7
8for (let i = start; i < end; i++) {
9 console.log(i) // prints 0 through 9
10}
In the C/C++ syntax, incrementing the counter is simply changing the increment parameter of the for
invocation.
1for (let i = start; i < end; i += 2) {
2 console.log(i) // prints 0, 2, 4, 6, 8
3}
4
5for (let i = end; i >= start; i -= 2) {
6 console.log(i) // prints 10, 8, 6, 4, 2, 0
7}
To break out of a for
loop early, JavaScript also uses the break
keyword.
1const start = 0
2const end = 10
3
4for (let i = start; i < end; i++) {
5 if (i > 4) break
6 console.log(i) // prints 0, 1, 2, 3, 4
7}