Control flow
While Loops
How JavaScript's while loop maps to Go's for used as a while loop (Go has no while keyword) — Rust, Swift, and Java all have while like JavaScript.
- Minimum versions
- Node.js ≥ 12.20Go ≥ 1.0Rust ≥ 1.58Swift ≥ 2.0Java ≥ 25
- Verified on
- Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1
Node.js code is an ES module: save it as .mjs or set "type": "module" in package.json.
Go has no while keyword. The same thing is achieved with for and just a condition, dropping the init and post parts entirely. Rust, Swift, and Java all have while just like JavaScript — of these five languages, Go is the only exception.
while in JavaScript, for in Go
let i = 0
while (i <= 5) {
console.log(i)
i++
}package main
import "fmt"
func main() {
i := 0
for i <= 5 {
fmt.Println(i)
i++
}
}fn main() {
let mut i = 0;
while i <= 5 {
println!("{i}");
i += 1;
}
}var i = 0
while i <= 5 {
print(i)
i += 1
}void main() {
int i = 0;
while (i <= 5) {
IO.println(i);
i++;
}
}0
1
2
3
4
5Reference: github.com/miguelmota/golang-for-nodejs-developers#while