ForEach Syntax in Swift, Kotlin and JavaScript

ForEach is a common pattern in programming modern programming languages.  Prior to ForEach, the standard approach to iterating over an array of objects was to use a for loop stepping from the first index to the last.

ForEach syntax has extra utility in languages that support many types of collections: a list iterated using ForEach doesn't need to have sequential indexes!

Swift

Iterating over a list of objects in a collection: forEach

let array = ["Hello", "World"]
for word in array {
  print(word)
}

To access the element index within the forEach execution block,  use the enumerated function. This can be done using either for or forEach. Note that when using enumerated, the index emitted is just a counter, so it will be emit an accurate accessor value only when used with zero-based arrays.

let array = ["Hello", "World"]
array.enumerated().forEach { (index, name) in
  print("\(word) is at index \(index)")
}

for (index, name) in array.enumerated() {
    print("\(index): \(name)")
}

Notable is a similarly named--but not the same--language construct used in SwiftUI for iterating over a collection that emits a list of SwiftUI views: ForEach

var filters = ["First", "Second", "Third"]()

// Emit three SwiftUI Buttons
ForEach(filters, id: \.self) { choice in
    Button(action: {
        print("Filter selected: \(choice)")
    }) {
        Text(choice)
    }
}

SwiftUI ForEach requires that each item in the collection be unique, and the id property can be passed in-line as in this example.

If the collection of items passed to ForEach conforms to the Swift Identifiable protocol, then it isn't necessary to specify the id property, since Swift will implicitly know which property to use to distinguish the uniqueness of items in the list.

Kotlin

Kotlin's forEach syntax is virtually identical to Swift's.

val array = listOf("Hello", "World")

array.forEach { word ->
  print(word)
}

To access the array index within the execution block:

val array = listOf("Hello", "World")

array.forEachIndexed{ index, word ->
  print("$word is at index $index")
}

JavaScript

In JavaScript, the syntax is similar to other languages, but note that ForEach is actually a function call, so don't forget the parentheses!

const array = [ "Hello", "World"]

array.forEach(word => {
  console.log(word)
})

While forEach is more modern and and a more natural way to think about iterating over lists, I often find using old-school index iteration in JavaScript simpler when used with arrays, since it doesn't have the complexity of being a function call executing a block in a separate scope:

const array = [ "Hello", "World"]

for (let i=0; i < array.length; i++) {
  console.log(array[i])
}