The magic comes from the Kotlin compiler and your project target. In a standard JVM-targeted Kotlin project, the compiler generates JVM-compatible bytecode that runs on the JVM and is intrinsically compatible with other JVM code.
When creating a Kotlin project that targets JavaScript, all of the Kotlin code within that project will be transpiled to JavaScript when you build the project. If you're unfamiliar with the termĀ transpile, it refers to the compilation of a programming language by converting it from one language to another. In a sense, the code is rewritten to match the target language. In this case, the Kotlin code you write is translated into compatible JavaScript that can then be consumed as if you had written any other JavaScript code. This includes any Kotlin code within your project, including the Kotlin standard library. However, this does not include any JVM-based code or libraries that are used. So, if you're consuming a Java library in your Kotlin code, you'll need to refactor that before it will be available in the transpiled JavaScript.
As with any programming language, there are often many ways to write functionally equivalent JavaScript code. When debugging or otherwise examining the JavaScript output of transpiled Kotlin, it's desirable to make that code as readable as possible. If the code looks like something a person would write, rather than something a compiler generates, it becomes easier to understand, debug, and reason about. To this end, JetBrains continues to work to ensure that the Kotlin compiler generates human-readable JavaScript during the transpiling phase.
Now that we understand that Kotlin is transpiled to JavaScript when a project is created that targets JavaScript, how do we actually target JavaScript when creating a new project? Let's see how this is done in the next section.