jsrosetta

Control flow

If/Else

How JavaScript's if/else if/else and ternary operator compare to Go (no ternary), Rust (if is an expression), and Swift/Java (both have a ternary).

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.

if/else if/else in Go reads almost identically to JavaScript — you just drop the parentheses around the condition. The biggest difference: Go has no ternary operator (? :), so you write it out with a variable and a plain if block instead. Rust also has no ternary operator, but if in Rust is an expression, so it reads more compactly than Go's version. Swift and Java both have a real ? : just like JavaScript.

Conditional branching

const array = [1, 2]
 
if (array) {
  console.log('array exists')
}
 
if (array.length === 2) {
  console.log('length is 2')
} else if (array.length === 1) {
  console.log('length is 1')
} else {
  console.log('length is other')
}
 
const isOddLength = array.length % 2 == 1 ? 'yes' : 'no'
 
console.log(isOddLength)
array exists
length is 2
no

Reference: github.com/miguelmota/golang-for-nodejs-developers#ifelse