Skip to content

Basics

Variables

Kotlin val maps to JavaScript const, and var maps to let.

val x = 42
var y = 0

Transpiles to:

const x = 42;
let y = 0;

Functions

Functions are transpiled to standard JavaScript function declarations.

fun greet(name: String): String {
    return "Hello, " + name
}

Transpiles to:

function greet(name) {
    return "Hello, " + name;
}

Control Flow

If-Else

if statements work as expected.

if (x < 0) {
    return -x
} else {
    return x
}

Transpiles to:

if (x < 0) {
    return -x;
}
else {
    return x;
}

When

Kotlin when expressions are transpiled to if/else if/else chains.

when (x) {
    1 -> println("One")
    2 -> println("Two")
    else -> println("Other")
}

Transpiles to:

if (x === 1) {
    println("One");
}
else if (x === 2) {
    println("Two");
}
else {
    println("Other");
}

When used as an expression, it is wrapped in an immediately invoked function expression (IIFE):

val result = when (x) {
    1 -> "One"
    else -> "Other"
}

Transpiles to:

const result = (() => {
    if (x === 1) {
        return "One";
    }
    else {
        return "Other";
    }
})();

Loops

For Loops

for loops over ranges are transpiled to standard for loops.

for (i in 1..n) {
    println(i)
}

Transpiles to:

for (let i = 1; i <= n; i++) {
    println(i);
}

Loops over collections use for...of.

for (item in items) {
    println(item)
}

Transpiles to:

for (const item of items) {
    println(item);
}

While Loops

while (i > 0) {
    i--
}

Transpiles to:

while (i > 0) {
    i--;
}

Operators

Equality

Kotlin's == and != always map to JavaScript's strict equality operators === and !==.

Elvis Operator

The elvis operator ?: maps to the JavaScript nullish coalescing operator ??.

val name = user?.name ?: "Guest"

Transpiles to:

const name = user?.name ?? "Guest";

String Templates

Kotlin string templates are transpiled to JavaScript template literals.

val message = "Hello, ${name}!"

Transpiles to:

const message = `Hello, ${name}!`;