Introducing the Nashorn JavaScript Engine

Share this article

Nashorn is a new JavaScript engine developed in the Java programming language by Oracle, released with Java 8. Nashorn’s goal is to implement a lightweight high-performance JavaScript runtime in Java with a native JVM. By making use of Nashorn, the developer can embed JavaScript in a Java application and also invoke Java methods and classes from the JavaScript code.

Key Takeaways

  • Nashorn is a high-performance JavaScript engine developed by Oracle in Java, aimed at implementing a lightweight JavaScript runtime in Java with a native JVM. It allows developers to embed JavaScript in a Java application and invoke Java methods and classes from the JavaScript code.
  • Nashorn is designed with a set of specific goals, including being based on ECMAScript-262 Edition 5.1 language specification, supporting the javax.script (JSR 223) API, allowing invocation of Java from JavaScript and vice versa, defining a command-line tool for evaluating JavaScript code, and having improved performance over its predecessor, Rhino.
  • With Nashorn, JavaScript can be used as a powerful shell-like scripting language, taking advantage of the simplicity of JavaScript and the rich API of Java. It can be used for client-side applications, server-side applications, mobile applications, or to set up a small Internet of Things (IoT).

Why Leave Rhino?

Rhino is the predecessor of Nashorn. It began as a project in 1997 at NetScape and got released in 1998.

There have been 16 years since the release of Rhino, and that JavaScript engine has lived its days. So the Java guys decided to have some fun by developing a new JavaScript engine from scratch instead of rewriting the existing one. This gave birth to Nashorn (fun fact: nashorn means rhino in German).

Almost everyone here has been using JavaScript in the browser, and some have been using it on the server (like Node.js), but Nashorn is developed for another purpose. By using Nashorn the developer can perform the magic of:

  • Running JavaScript as native Desktop code.
  • Using JavaScript for shell scripting.
  • Call Java classes and methods from JavaScript code.

The Goals of Nashorn

When Nashorn was designed, the developers decided a set of goals for it:

  • It should be based on ECMAScript-262 Edition 5.1 language specification, and must pass the ECMAScript-262 compliance tests.
  • It should support the javax.script (JSR 223) API.
  • It should allow invoking Java from JavaScript and vice-versa.
  • It should define a command-line tool, jjs for evaluating JavaScript code in “shebang” scripts (that normally start with #!/bin/sh), here documents, and edit strings.
  • Its performance should be significantly better than Rhino.
  • It should have no security risks.

Furthermore, no one decided that Nashorn will not include debugging and not support CSS and JavaScript libraries/frameworks. This means Nashorn can be implemented in a browser without being a nightmare.

JavaScript in a (nut)Shell

In order to use JavaScript in the shell by using Nashorn’s jjs tool, you should first install the JDK8, which you can download for free. To test its installation, execute:

>_ javac -version
# it should echo
# java version "1.8.x"
jjs -version
# it should echo
# nashorn 1.8.x
jjs>

If you face any problems with the first or the second command, try adding JDK in the path

Now you can use JavaScript as a shell script. Check out this simple example:

jjs> var a = 1
jjs> var b = 4
jjs> print (a+b)
5
jjs>

As you may have already figured out, you don’t have to write the code into the jjs shell. You can write the code into a JavaScript source file, and then call it from the shell. Consider the following JavaScript code:

var isPrime = function(num) {
    if (isNaN(num) || !isFinite(num) || num < 2) 
        return false;

    var m = Math.sqrt(num);

    for (var i = 2;i <= m; i++) 
        if (num % i === 0) 
            return false;

    return true;
}

var numbers = [ 2, 3, 4, 5, 6, 7, 8, 9, 10 ];

for (var i = 0; i < numbers.length; i++) {
    if (isPrime(numbers[i]))
        print(numbers[i] + " is prime");
    else
        print(numbers[i] + " is not prime");
}

Assuming the code is on a file called prime.js, we can run it in the shell, by executing:

>_ jjs prime.js
2 is prime
3 is prime
4 is not prime
5 is prime
6 is not prime
7 is prime
8 is not prime
9 is not prime
10 is not prime

This may remind you of Python code or bash scripting, but it is JavaScript. And to make it more bash-like, Nashorn gives the arguments variable to extract the command line arguments. Consider this example:

if (arguments.length === 0)
    print("No command-line arguments.");
else {
    print("Called with these command-line arguments:");

    for each (cli_arg in arguments) {
        print(cli_arg);
    }
}

Running it will give this output (arguments go after --):

>_ jjs cliargs.js
No command-line arguments.

>_ jjs cliargs.js -- a b "c d e"
Called with these command-line arguments:
a
b
c d e

Also, JavaScript can use Java classes and methods. See this example of a multithreaded JavaScript code:

var Thread = Java.type("java.lang.Thread"); 
var Runnable = Java.type('java.lang.Runnable');

var Run1 = Java.extend(Runnable, { 
    run: function() { 
        print("One thread");
        print("One thread");
    } 
}); 

new Thread(function() {
    print("Another thread");
    print("Another thread");
    print("Another thread");
}).start()

new Thread(new Run1()).start();

And the output would be:

Another thread
Another thread
One thread
One thread
Another thread

You can tell by the output that the code is multithreaded. By using Java.type("java.lang.Thread"); we can call Java classes inside the JavaScript code. Nashorn allows even going in the other direction, calling JavaScript code inside Java code.

package j2js.example;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Main {

    public static void main(String[] args) {

        ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");
        
        try {
            nashorn.eval("print('Am I Java or JavaScript?')");
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

}

This example just prints the Am I Java or JavaScript? question on line 14, but this is the simplest example of JavaScript code into Java. One can read the whole source code from the JavaScript file, using Java methods, and then pass that code as a String parameter to the eval() method. This would make the JavaScript code to execute inside Java.

Conclusion

Nowadays JavaScript is everywhere! You may use it for client-side applications, server-side applications, and better yet, sometimes for both client and server. You may use it for mobile applications or to set up a small IoT. And now, with Nashorn, you may use it as a powerful shell-like scripting language, by taking advantage of the simplicity of JavaScript and the rich API of Java.

Frequently Asked Questions about Nashorn JavaScript Engine

What is the Nashorn JavaScript Engine?

The Nashorn JavaScript Engine is a high-performance JavaScript engine developed by Oracle for Java Virtual Machine (JVM). It is designed to execute JavaScript code natively within a JVM, allowing Java and JavaScript to interact seamlessly. Nashorn provides significant performance improvements over its predecessor, Rhino, and includes support for newer JavaScript features.

How does Nashorn compare to other JavaScript engines?

Nashorn is unique in that it is designed specifically for the JVM. This allows it to take advantage of the JVM’s robustness, maturity, and performance characteristics. It also provides a direct bridge between Java and JavaScript, enabling seamless interaction between the two languages. However, it’s worth noting that Nashorn is not as widely used as other JavaScript engines like V8 (used in Node.js and Chrome) or SpiderMonkey (used in Firefox).

How can I use Nashorn in my Java application?

To use Nashorn in your Java application, you need to use the ScriptEngineManager class to create a new instance of the Nashorn ScriptEngine. You can then use the eval() method of the ScriptEngine to execute JavaScript code. Here’s a simple example:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Main {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
engine.eval("print('Hello, World!');");
}
}

What are the benefits of using Nashorn?

Nashorn provides several benefits. Firstly, it allows you to execute JavaScript code natively within a JVM, which can lead to performance improvements. Secondly, it provides a seamless bridge between Java and JavaScript, allowing you to use JavaScript libraries and frameworks within your Java applications. Finally, Nashorn supports newer JavaScript features, which can make your JavaScript code more efficient and easier to write.

Is Nashorn still maintained by Oracle?

As of JDK 11, Nashorn has been deprecated by Oracle. This means that while it is still included in the JDK, it is no longer actively developed or maintained. Oracle has recommended that developers start looking for alternatives.

What are some alternatives to Nashorn?

There are several alternatives to Nashorn, including GraalVM, which is a high-performance runtime that provides support for several languages including JavaScript. Other alternatives include Rhino, which is another JavaScript engine for the JVM, and Node.js, which is a popular JavaScript runtime built on Chrome’s V8 JavaScript engine.

Can I use ES6 features with Nashorn?

Nashorn provides support for some ES6 features, but not all. This includes features like let and const declarations, arrow functions, and template strings. However, features like modules, classes, and promises are not supported.

How can I debug JavaScript code executed by Nashorn?

Nashorn includes a command-line tool called jjs, which can be used to execute and debug JavaScript code. You can also use the Java Debugger (jdb) to debug JavaScript code executed by Nashorn.

Can I use Node.js modules with Nashorn?

While Nashorn does not natively support Node.js modules, there are libraries available that provide this functionality. One such library is Avatar.js, which provides a Node.js-compatible API and module system on top of Nashorn.

How can I call Java methods from JavaScript code executed by Nashorn?

Nashorn provides a seamless bridge between Java and JavaScript, allowing you to call Java methods directly from your JavaScript code. Here’s a simple example:

var System = Java.type('java.lang.System');
System.out.println('Hello, World!');

Aldo ZiflajAldo Ziflaj
View Author

Aldo is a Code-Lover and a student of Computer Engineering from Albania. His short-term goal is that of becoming a full-stack developer, focusing on Android, Ruby technologies and DevOps techniques.

ColinIjavaNashorn
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week