Using the compiled JavaScript

A question that arises foremost is what we can do with our JavaScript once it's been transpiled from Kotlin. The simplest usage is to load the resulting script into an HTML page and execute whatever code we've defined in our main function.

For example, we can define a Kotlin main() function that prints to the console, as in the following example:

fun main(args: Array<String>) {
val message = "Hello Kotlin JavaScript"
println(message)
}
// outputs "Hello Kotlin JavaScript"

We can load the transpiled JavaScript equivalent of this code using a <script> tag with an HTML document to print out "Hello Kotlin JavaScript" to the console in our browser. We will see exactly how to do this in the very next section.

Beyond writing simple scripts, we could define model objects or business logic within Kotlin and then load those into our web app or server as well. Additionally, these scripts, functions, and models can be used in conjunction with other popular JavaScript frameworks, such as React. We'll discuss this in more detail in the Integrating with existing JavaScript section of this chapter.

Now, before diving into creating our own Kotlin project that targets JavaScript, let's explore why you might want to consider using Kotlin when targeting JavaScript.