Access Keys:
Skip to content (Access Key - 0)
Nashorn extensions
Attachments: • Added by Sundararajan Athijegannathan, last edited by Sundararajan Athijegannathan on Jun 30, 2015  (view change)
  • None

Nashorn Syntax Extensions

Nashorn implements ECMAScript 5.1 specification

HTML non-normative version of the spec is here:

Nashorn implements number of syntactic and API extensions as well. This page describes syntax and API extensions of nashorn implementation. A number of syntax and API extensions are enabled only when scripting mode is enabled. Scripting mode is turned on by nashorn option "-scripting". Whenever a syntax or an API extension is available only in -scripting mode, it is noted so in this document.

Conditional catch clauses

This Mozilla JavaScript 1.4 extension is also supported by Nashorn. A single try.. statement can have more than one catch clause each with it's own catch-condition.

Conditional catch clause example

Function expression closures

This Mozilla JavaScript 1.8 extension is also supported by Nashorn. This syntax allows braces and return keyword to be dropped when defining simple one-liner functions. See also


Closure expression example

For each expressions

This is a Mozilla JavaScript 1.6 extension supported by Nashorn. ECMAScript iterates over property names or array indices of an object. loop iterates over property values of an object rather than property names/indices. See also


for each loop

for..each works on Java arrays as well as any Java Iterable objects.


for each Java arrays example
for..each Java map

New expression with last argument after ")"

This is another Rhino extension supported by Nashorn. In a new Constructor(x, y) expression, the last argument can be specified after ")" if it happens to be an object literal. Example:

new anonymous class-like syntax

Anonymous function statements

Top-level function statements can be anonymous. Example:


anonymous function statements

How do you call it then? Say if you had evaluated the above code by "eval" or script engine's "eval" call from Java, you can get the return value to be the function object - which can be invoked later.

Multi-line string literals (-scripting mode only)

Nashorn supports multi-line string literals with Unix shell's here-doc syntax. Example:

multi-line string literals

String interpolation (-scripting mode only)

Expressions can be specified inside string literals with the syntax ${expression}. The string value is computed by substituting value of expressions for ${expression} in the string.

String expression interpolation

Back-quote exec expressions (-scripting mode only)

Nashorn supports Unix shell like back quote strings. Back quoted strings are evaluated by executing the programs mentioned in the string and returning value produced by the 'exec'-ed program.

back quote exec strings

Shell script style hash comments (-scripting mode only)

In -scripting mode, nashorn accept shell script style # (hash) single line comments.

# comment example

Nashorn supports shebang scripting. You need to create a link to jjs from your platform executable directory like /usr/bin as shown below.

Shebang scripts

For shebang nashorn scripts, -scripting mode is automatically enabled.

Switching off syntax extensions

Nashorn option --no-syntax-extensions (or it's short form -nse) can be used to switch off syntax extensions of nashorn. With syntax extensions switched off, only ECMAScript standard syntax is supported. Note that even when -scripting mode is on, -nse switches off scripting syntax extensions as well. Also note that API extensions are still enabled even -nse is specified.

Nashorn script API extensions

__proto__ property

Like other ECMAScript implementations (like Rhino, v8) Nashorn supports mutable __proto__ magic property to read and write prototype of a given object. See also

__proto__ is deprecated. Please avoid using __proto__. Use Object.getPrototypeOf and Object.setPrototypeOf instead.

Object.setPrototypeOf(obj, newProto)

ECMAScript specifies Object.getPrototypeOf(obj) function to get prototype of the given object. This Object.setPrototypeOf is a nashorn specific extension that allows prototype of an object to be set as newProto. Object.setPrototypeOf is one of proposed extensions in ECMAScript 6.

See also


Any object can have this "property missing" hook method. When a property accessed is not found on the object, this __noSuchProperty__ hook will be called.



Any object can have this "method missing" hook method. When a method is called is not found on the object, this __noSuchMethod__ hook will be called.


Typed Arrays

Nashorn implements typed arrays as specified at For a tutorial presentation, please check out (which includes non-standard StringView which is not implemented by nashorn). Among the typed array constructors, DataView ( ) is not implemented in jdk8's nashorn. DataView is included in jdk8u-dev and so is expected to make it into jdk8u20 release.


Object.bindProperties lets you bind properties of one object to another object. Example:


The bound object need not be a script object. It could be a Java object as well - usual Java bean style getter/setter properties will be bound. Also a property only with getter will be bound as read-only property.

The source object bound can be a ScriptObject or a ScriptOjectMirror.
null or undefined source object results in TypeError being thrown.

Limitations of property binding:

* Only enumerable, immediate (not proto inherited) properties of the source object are bound.
* If the target object already contains a property called "foo", the source's "foo" is skipped (not bound). * Properties added to the source object after binding to the target are not bound. * Property configuration changes on the source object (or on the target) is not propagated.
* Delete of property on the target (or the source) is not propagated -
only the property value is set to 'undefined' if the property happens to be a data property.
It is recommended that the bound properties be treated as non-configurable
properties to avoid surprises.

Extensions of Error objects, Error.prototype and Error constructor

Nashorn extends ECMAScript Error (or subtype) objects with the following properties.

  • lineNumber - source code line number from which error object was thrown
  • columnNumber  -  source code column number from which error object was thrown
  • fileName  - source script file name
  • stack - script stack trace as a string

In addition to this Error.prototype has the following extension functions as well.

  • Error.prototype.printStackTrace() - prints full stack trace (including all Java frames) from where error was thrown from
  • Error.prototype.getStackTrace() -  returns an array of java.lang.StackTraceElement instance for ECMAScript frames only.

Error constructor includes dumpStack() function property

  • Error.dumpStack() - prints stack trace of the current thread - just like java.lang.Thread.dumpStack()
Error extensions

String.prototype extensions

String.prototype.trimLeft -

String.prototype.trimRight -


Extension properties, functions in global object

__FILE__ , __LINE__, __DIR__

Current executing script file, line, directory of the script can be accessed by these global (read-only) properties. This is useful in debug/tracing scripts. __DIR__ can be used like Unix 'dirname' command. Script can load script-file relative path resources using __DIR__.

_FILE_ and _LINE_

print function

print function prints it's arguments (after converting those to Strings) on standard output


load function

Loads and evaluates script from a file or a URL or a script object. Examples:

load function

loadWithNewGlobal function

loadWithNewGlobal is almost like the function "load" in that it loads script from a file or a URL or a script object. But unlike 'load', loadWithNewGlobal creates a fresh ECMAScript global scope object and loads the script into it. The loaded script's global definitions go into the fresh global scope. Also, the loaded script's modifications of builtin objects (like String.prototype.indexOf) is not reflected in the caller's global scope – these are affected in the newly created global scope.


exit and quit functions

These synonymous functions exit the current process with specified (optional) exit code.


Packages, java, javax, javafx, com, edu, org

Packages and related objects are there to support java package, class access from script. The properties of the Packages variable are all the top-level Java packages, such as java and javax etc.

jjs session of Packages, classes

JavaImporter constructor

Many times you may want to import many Java packages – but without having to "pollute" global scope. JavaImporter helps in such situations.

JavaImporter in 'with' statement example

Java object

"Java" global property is a script object that defines useful functions for script-to-Java interface.

Java.type function

Given a name of a Java type, returns an object representing that type in Nashorn. The Java class of the objects used to represent Java types in Nashorn is not Class but rather StaticClass. They are the objects that you can use with the new operator to create new instances of the class as well as to access static members of the class. In Nashorn, Class objects are just regular Java objects that aren't treated specially. Instead of them, StaticClass instances - which we sometimes refer to as "Java type objects" are used as constructors with the new operator, and they expose static fields, properties, and methods. While this might seem confusing at first, it actually closely matches the Java language: you use a different expression (e.g. as an argument in "new" and to address statics, and it is distinct from the Class object (e.g. To get StaticClass object corresponding to a Java Class object, you can use "static" property. Below we cover in details the properties of the type objects.


If the type is abstract, you can instantiate an anonymous subclass of it using an argument list that is applicable to any of its public or protected constructors, but inserting a JavaScript object with functions properties that provide JavaScript implementations of the abstract methods. If method names are overloaded, the JavaScript function will provide implementation for all overloads. E.g.:

new on abstract class

Nashorn supports a syntactic extension where a "new" expression followed by an argument is identical to invoking the constructor and passing the argument to it, so you can write the above example also as:

anonymous class like expression

which is very similar to Java anonymous inner class definition. On the other hand, if the type is an abstract type with a single abstract method (commonly referred to as a "SAM type") or all abstract methods it has share the same overloaded name), then instead of an object, you can just pass a function, so the above example can become even more simplified to:


The use of functions can be taken even further; if you are invoking a Java method that takes a SAM type, you can just pass in a function object, and Nashorn will know what you meant:

SAM function conversion

Here, Timer.schedule() expects a TimerTask as its argument, so Nashorn creates an instance of a TimerTask subclass and uses the passed function to implement its only abstract method, run(). In this usage though, you can't use non-default constructors; the type must be either an interface, or must have a protected or public no-arg constructor.

Java.extend function

Java.extend function returns a type object for a subclass of the specified Java class (or implementation of the specified interface) that acts as a script-to-Java adapter for it. Note that you can also implement interfaces and subclass abstract classes using new operator on a type object for an interface or abstract class. However, to extend a non-abstract class, you will have to use this method. Example:

Java.extend examples

Java.extend - larger example


Java.from function

Given a Java array or Collection, this function returns a JavaScript array with a shallow copy of its contents. Note that in most cases, you can use Java arrays and lists natively in Nashorn; in cases where for some reason you need to have an actual JavaScript native array (e.g. to work with the array comprehensions functions), you will want to use this method. Example:

Java.from examples function

Given a script object and a Java type, converts the script object into the desired Java type. Currently it performs shallow creation of Java arrays, as well as wrapping of objects in Lists and Dequeues. Example: example

Java.super function

When given an object created using Java.extend() or equivalent mechanism (that is, any JavaScript-to-Java adapter), Java.super returns an object that can be used to invoke superclass methods on that object. E.g.:

Java.super example

Java subclassing - Java.extend and Java.super - a larger example:

Java.extend and Java.super - larger example

Java.synchronized function

Returns synchronized wrapper version of the given ECMAScript function.

Java.synchronized example

Java.asJSONCompatible function

This function accepts a script object and returns an object that is compatible with Java JSON libraries expectations; namely, that if it itself, or any object transitively reachable through it is a JavaScript array,then such objects will be exposed as JSObject that also implements the List interface for exposing the array elements.

An explicit API is required as otherwise Nashorn exposes all objects externally as JSObjects that also implement the Map interface instead. By using this method, arrays will be exposed as Lists and all other objects as Maps.

This API is since jdk 8u60+ and jdk 9. A simple example that uses Java.asJSONCompatible function:

Java.asJSONCompatible example

Special treatment of objects of specific Java classes

Java Map keys as properties

Nashorn allows java.util.Map instances to be treated like a script object - in that it allows indexed, property access to Map's keys.

java.util.Map keys as properties example

Java List element access/update via array index access/update syntax

Elements of java.util.List objects can be access as though those are array elements - array like indexed element access and update is supported. "length" property can be used on List objects to get size of the list.

Java List elements via array index access

Lambdas, SAM types and Script functions

Every function is a lambda and a SAM type object

Where ever a JDK8 lambda or SAM  (single-abstract-method) type is required, an ECMAScript function can be passed as argument. Nashorn will auto-convert a script function to a lambda object or any SAM interface implementing object.

lambda, SAM example

Every lambda is a script function

Any Java object that is an instance of lambda type can be treated like a script function.

lambda as function example

Explicit method selection

When you call java method from script, Nashorn automatically selects the most specific overload variant of that method (based on the runtime type of the actual arguments passed – with appropriate type conversions as needed). But sometimes you may want to manually select a specific overload variant. If so, you can specify method signature along with the method name.


Explicit method signature

Explicit constructor selection (jdk9)

With jdk9, explicit constructor overload selection is also supported. See Index selection of overloaded java new constructors and Explicit constructor overload selection should work with StaticClass as well

Explicit constructor selection (jdk9 only)


--no-java option

--no-java options can be used to switch-off Java specific extensions like "Java", "Packages" object etc.

Script Proxy implementation

Sometimes you may want to create a script friendly proxy object adapting another object. You can implement such a proxy in Java code or JavaScript code.

Plugging-in your own JSObject

Nashorn exposes script objects as an object of jdk.nashorn.api.scripting.JSObject to java code. It is also possible to provide your own jdk.nashorn.api.scripting.JSObject implementation and nashorn will treat such objects specially (by calling magic methods for property getter, setter, delete etc.)

JSObject implementation example

JS example using the above JSObject implementation is as follows:

JSObject usage example

JSAdapter constructor

JSAdapter supports java.lang.reflect.Proxy-like proxy mechanism for script objects. i.e., it allows script proxy

objects be implemented in script itself.


JSAdapter example

Scripting mode extension objects and functions

$ARG (-scripting mode only)

This global object can be used to access the arguments passed to the script, similar to how the arguments object is used, for example:

$ARG example

echo (-scripting mode only)

This is a synonym to "print" function -  the values passed in as arguments to be converted to strings, printed to stdout separated by spaces, and followed by a new line.


echo example

$ENV (-scripting mode only)

$ENV object exposes OS process environment variables to script.

$ENV example

$EXEC (-scripting mode only)

This global function launches processes to run commands, for example:

$EXEC example

If the command does not require any input, you can launch a process using the backtick string notation. For example, instead of $EXEC("ls -l"), you can use `ls -l`.

$OUT (-scripting mode only)

This global object is used to store the latest standard output (stdout) of the process spawned by $EXEC. For example, the result of $EXEC() is saved to $OUT.

$EXEC example with $OUT usage

$ERR (-scripting mode only)

This global object is used to store the latest standard error (stderr) of the process spawned by $EXEC.

$EXIT (-scripting mode only)

This global object is used to store the exit code of the process spawned by $EXEC. If the exit code is not zero, then the process failed

$OPTIONS (-scripting mode only)

This property exposes command line options passed to nashorn "command line".

$OPTIONS usage

readFully (-scripting mode only)

This function reads the entire contents of a file passed in as a string argument and sends it to stdout, or you can assign the result to a variable.

readFully example

readLine (-scripting mode only)

This function reads one line of input from stdin and sends it to stdout, or you can assign the result to a variable. You can also pass a string to the readLine() function to get a prompt line as in the following example:

readLine example

Nashorn call site tracing and profiling

Nashorn  supports callsite tracing and profile jjs (jjs tool) options via command line options -tcs and -pcs. You can pass these to jjs tool or set these options via "nashorn.args" System property. But these options produce trace, profile output for all scripts that are run. To avoid having to look at too much trace output (or too big NashornProfile.txt file), nashorn allows per script or per function tracing, profiling via user directives.

You can include nashorn specific user directives (  directive prologues ) at the start of a source script or at the start of a script function as shown below:

tracing, profiling directives
Profile directive

Just like -pcs option, profile directive will produce NashornProfile.txt file in the current dir of the application. But

profiling is enabled per script or per function only rather than globally. These nashorn directives are enabled only in nashorn debug mode. So, these are effective only when jjs is run  -J-Dnashorn.debug option set or script engine is initialized after "nashorn.debug" system property is set to true. Also, this feature is available only on jdk 8u40 + and jdk 9 only.