# Use JavaScript code from Kotlin Kotlin was first designed for easy interoperation with the Java platform: it sees Java classes as Kotlin classes, and Java sees Kotlin classes as Java classes. However, JavaScript is a dynamically typed language, which means it does not check types at compile time. You can freely talk to JavaScript from Kotlin via [dynamic](dynamic-type.html) types. If you want to use the full power of the Kotlin type system, you can create external declarations for JavaScript libraries which will be understood by the Kotlin compiler and the surrounding tooling. ## Inline JavaScript You can inline JavaScript code into your Kotlin code using the [js()](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.js/js.html) function: ```KOTLIN fun jsTypeOf(o: Any): String { return js("typeof o") } ``` JavaScript code inlining has full support for [ES2015 features](js-project-setup.html#set-an-ecmascript-target), including: * `const` and `let` variable declarations * ES classes * Generators * Lambdas ([arrow functions](whatsnew21.html#support-for-generating-es2015-arrow-functions)) * Spread and rest operators * Template strings Because the parameter of `js` is parsed at compile time and translated to JavaScript code "as-is", it must be a string constant. So, the following code is incorrect: ```KOTLIN fun jsTypeOf(o: Any): String { return js(getTypeof() + " o") // Error: Argument must be a string constant // The compiler cannot evaluate string concatenations } fun getTypeof() = "typeof" ``` Instead, for example to inline the rest operator, use a string constant: ```KOTLIN fun runSumExample() { val sum = js("(...nums) => nums.reduce((a, b) => a + b, 0)") println(sum(1, 2, 3, 4)) } ``` Note: Invoking `js()` returns a result of [dynamic](dynamic-type.html) type, which doesn't provide type safety at compile time. ## `external` modifier To tell Kotlin that a certain declaration is written in pure JavaScript, you should mark it with the `external` modifier. When the compiler sees such a declaration, it assumes that the implementation for the corresponding class, function or property is provided externally (by the developer or via an [npm dependency](js-project-setup.html#npm-dependencies)), and therefore does not try to generate any JavaScript code from the declaration. This is also why `external` declarations can't have a body. For example: ```KOTLIN external fun alert(message: Any?): Unit external class Node { val firstChild: Node fun append(child: Node): Node fun removeChild(child: Node): Node // etc } external val window: Window ``` Note that the `external` modifier is inherited by nested declarations. This is why in the example `Node` class, there is no `external` modifier before member functions and properties. The `external` modifier is only allowed on package-level declarations. You can't declare an `external` member of a non-`external` class. ### Declare (static) members of a class In JavaScript, you can define members either on a prototype or a class itself: ```JAVASCRIPT function MyClass() { ... } MyClass.sharedMember = function() { /* implementation */ }; MyClass.prototype.ownMember = function() { /* implementation */ }; ``` There is no such syntax in Kotlin. However, in Kotlin we have [companion](object-declarations.html#companion-objects) objects. Kotlin treats companion objects of `external` classes in a special way: instead of expecting an object, it assumes members of companion objects to be members of the class itself. `MyClass` from the example above can be described as follows: ```KOTLIN external class MyClass { companion object { fun sharedMember() } fun ownMember() } ``` ### Declare parameters with default values If you are writing an external declaration for a JavaScript function which has a parameter with a default value, use `definedExternally`. This delegates the generation of the default values to the JavaScript function itself: ```KOTLIN external fun myFunWithOptionalArgs( x: Int, y: String = definedExternally, z: String = definedExternally ) ``` With this external declaration, you can call `myFunWithOptionalArgs` with one required argument and two optional arguments, where the default values are calculated by the JavaScript implementation of `myFunWithOptionalArgs`. ### Extend JavaScript classes You can easily extend JavaScript classes as if they were Kotlin classes. Just define an `external open` class and extend it by a non-`external` class. For example: ```KOTLIN open external class Foo { open fun run() fun stop() } class Bar : Foo() { override fun run() { window.alert("Running!") } fun restart() { window.alert("Restarting") } } ``` There are some limitations: * When a function of an external base class is overloaded by signature, you can't override it in a derived class. * You can't override a function including parameters with default values. * Non-external classes can't be extended by external classes. ### external interfaces JavaScript does not have the concept of interfaces. When a function expects its parameter to support two methods `foo` and `bar`, you would just pass in an object that actually has these methods. You can use interfaces to express this concept in statically typed Kotlin: ```KOTLIN external interface HasFooAndBar { fun foo() fun bar() } external fun myFunction(p: HasFooAndBar) ``` A typical use case for external interfaces is to describe settings objects. For example: ```KOTLIN external interface JQueryAjaxSettings { var async: Boolean var cache: Boolean var complete: (JQueryXHR, String) -> Unit // etc } fun JQueryAjaxSettings(): JQueryAjaxSettings = js("{}") external class JQuery { companion object { fun get(settings: JQueryAjaxSettings): JQueryXHR } } fun sendQuery() { JQuery.get(JQueryAjaxSettings().apply { complete = { (xhr, data) -> window.alert("Request complete") } }) } ``` External interfaces have some restrictions: * They can't be used on the right-hand side of `is` checks. * They can't be passed as reified type arguments. * They can't be used in class literal expressions (such as `I::class`). * `as` casts to external interfaces always succeed. Casting to external interfaces produces the "Unchecked cast to external interface" compile time warning. The warning can be suppressed with the `@Suppress("UNCHECKED_CAST_TO_EXTERNAL_INTERFACE")` annotation. IntelliJ IDEA can also automatically generate the `@Suppress` annotation. Open the intentions menu via the light bulb icon or Alt-Enter, and click the small arrow next to the "Unchecked cast to external interface" inspection. Here, you can select the suppression scope, and your IDE will add the annotation to your file accordingly. ### Casts In addition to the ["unsafe" cast operator](typecasts.html#unsafe-cast-operator) `as`, which throws a `ClassCastException` in case a cast is not possible, Kotlin/JS also provides [unsafeCast<T>()](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.js/unsafe-cast.html). When using `unsafeCast`, no type checking is done at all during runtime. For example, consider the following two methods: ```KOTLIN fun usingUnsafeCast(s: Any) = s.unsafeCast() fun usingAsOperator(s: Any) = s as String ``` They will be compiled accordingly: ```JAVASCRIPT function usingUnsafeCast(s) { return s; } function usingAsOperator(s) { var tmp$; return typeof (tmp$ = s) === 'string' ? tmp$ : throwCCE(); } ``` ## Equality Kotlin/JS has particular semantics for equality checks compared to other platforms. In Kotlin/JS, the Kotlin [referential equality](equality.html#referential-equality) operator (`===`) always translates to the JavaScript [strict equality](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator (`===`). The JavaScript `===` operator checks not only that two values are equal but also that the types of these two values are equal: ```KOTLIN fun main() { val name = "kotlin" val value1 = name.substring(0, 1) val value2 = name.substring(0, 1) println(value1 === value2) // Prints 'true' on Kotlin/JS // Prints 'false' on other platforms } ``` Also, in Kotlin/JS, the [Byte, Short, Int, Float, and Double](js-to-kotlin-interop.html#kotlin-types-in-javascript) numeric types are all represented with the `Number` JavaScript type in runtime. Therefore, the values of these five types are indistinguishable: ```KOTLIN fun main() { println(1.0 as Any === 1 as Any) // Prints 'true' on Kotlin/JS // Prints 'false' on other platforms } ``` Tip: For more information about equality in Kotlin, see the [Equality](equality.html) documentation.