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.

let start = 0
let end = 10

for i in start ... end {
  print(i)  // prints 0 through 10
}

for i in start ..< end {
  print(i)  // prints 0 through 9
}

To increment the counter other than by 1, Swift has a stride keyword.

let start = 0
let end = 10

for i in stride(from: start, to: end, by: 2) {
    print(i)	// prints 0, 2, 4, 6, 8 (10 is not included)
}

for i in stride(from: end, to: start, by: -2) {
    print(i)    // prints 10, 8, 6, 4, 2 (0 is not included)
}

To break out of a for loop early, Swift uses the break keyword.

let start = 0
let end = 10

for i in start...end {
    if i > 4 {
        break
    }
    print(i)    // prints 0, 1, 2, 3, 4
}

Kotlin

Kotlin uses a similar range operator for the inclusive range, and the until keyword for a non-inclusive range.

val start = 0
val end = 10

for (i in start..end) {
	print(i)	// prints 0 through 10
}
for (i in start until end) {      
	print(i) 	// prints 0 through 9
}

To increment the counter by other than 1, Kotlin uses the step keyword.

val start = 0
val end = 10

for (i in end downTo start step 2) {
    print(i)	// prints 10, 8, 6, 4, 2, 0
}

for (i in start..end step 2) {      
    print(i)	// prints 0, 2, 4, 6, 8, 10
}

To break out of a for loop early, Kotlin uses the break keyword.

val start = 0
val end = 10
        
for (i in start..end) {      
    if (i > 4) break
    print(i)	// prints 0, 1, 2, 3, 4
}

JavaScript

JavaScript follows the traditional C/C++ for loop syntax.

const start = 0
const end = 10

for (let i = start; i <= end; i++) {
  console.log(i)	// prints 0 through 10
}

for (let i = start; i < end; i++) {
  console.log(i)	// prints 0 through 9
}

In the C/C++ syntax, incrementing the counter is simply changing the increment parameter of the for invocation.

for (let i = start; i < end; i += 2) {
  console.log(i)	// prints 0, 2, 4, 6, 8
}

for (let i = end; i >= start; i -= 2) {
  console.log(i)	// prints 10, 8, 6, 4, 2, 0
}

To break out of a for loop early, JavaScript also uses the break keyword.

const start = 0
const end = 10

for (let i = start; i < end; i++) {
  if (i > 4) break
  console.log(i)	// prints 0, 1, 2, 3, 4
}