js

external fun js(code: String): dynamic(source)

Puts the given piece of a JavaScript code right into the calling function. The compiler replaces call to js(...) code with the string constant provided as a parameter.

Example:

fun logToConsole(message: String): Unit {
js("console.log(message)")
}

Since Kotlin

1.1

Parameters

code

the piece of JavaScript code to put to the generated code. Must be a compile-time constant, otherwise compiler produces error message. You can safely refer to local variables of calling function (but not to local variables of outer functions), including parameters. You can't refer to functions, properties and classes by their short names.


val <T : Any> KClass<T>.js: JsClass<T>(source)

Obtains a constructor reference for the given KClass.

Since Kotlin

1.1
external fun js(code: String): Nothing(source)

This function allows you to incorporate JavaScript code into Kotlin/Wasm codebase. It is used to implement top-level functions and initialize top-level properties.

It is important to note, that calls to js function should be the only expression in a function body or a property initializer.

code parameter should be a compile-time constant.

When used in an expression context, code should contain a single JavaScript expression. For example:

val version: String = js("process.version")
fun newEmptyJsArray(): JsValue = js("[]")

When used in a function body, code is expected to be a list of JavaScript statements. For example:

fun log(message1: String, message2: String) {
js("""
console.log(message1);
console.log(message2);
""")
}

You can use parameters of calling function in JavaScript code. However, other Kotlin declarations are not visible inside the code block.

Since Kotlin

1.9