Nashorn: JavaScript made great in Java 8

JavaScript on the JVM is better and faster but not always friendlier with Nashorn, the rebuilt JavaScript interpreter

Page 3 of 4

Running JavaScript scripts
Why the two command-line tools for running JavaScript scripts? I'm not completely clear on what the development team was thinking, but jjs has capabilities that jrunscript doesn't, and jrunscript has an initialization file. Below are a few simple examples of jjs and jrunscript use.

$ jrunscript
nashorn> alert("hello, InfoWorld");
script error: ReferenceError: "alert" is not defined in <STDIN> at line number 1

This doesn't work because alert() is a browser/DOM function. D'oh! I could have sworn that worked in Rhino, though.

nashorn> print("Hello, InfoWorld");
Hello, InfoWorld

This does work because print() is a core JavaScript function.

nashorn> var a = 1;
nashorn> var b = "1";
nashorn> print (a+b);
nashorn> print(a+a);
nashorn> quit();

In other words, we have a basic REPL (read-execute-print-loop command-line) environment for JavaScript here. If you're surprised by the answer to a+b, consider this:

nashorn> print (typeof(a+b));

That's a charming side effect of the loose typing and overloading of the "+" operator in JavaScript. It's correct behavior according to the JavaScript specification, not a bug.

Nashorn supports the "#" character as a leading line comment marker, so jjs and jrunscript can be used in executable "shebang" scripts written in JavaScript. On a Mac or Linux, you'll have to mark the JavaScript file as executable with the chmod utility to make it runnable.

You'll find a scripting mode in jjs that jrunscript seems to lack. In scripting mode, expressions inside back-ticks are passed to the outer shell for evaluation:

$ jjs -scripting
jjs> print ('ls');
Applications (Parallels)
Creative Cloud Files


Scripting mode also enables an extension for "heredocs," which are basically multiline strings in a format familiar to Perl and Ruby programmers.

By the way, the arrow keys on the Mac keyboard don't work properly for line editing in the jjs shell. But there is a hack for that: You can brew install rlwrap and use that as part of your alias for jjs in your .bashrc or .zshrc file.

| 1 2 3 4 Page 3