Scripting in Java Tutorial - Scripting in Java Nashorn

Nashorn is a runtime implementation of the ECMAScript 5.1 specification on the JVM.

Nashorn is 100 percent compliant with the ECMAScript 5.1.

With Nashorn we can use Java libraries inside scripts.

Nashorn has its own syntax and constructs.

Strict and Nonstrict Modes

Nashorn can operate in two modes: strict and nonstrict.

Some features of ECMAScript that are error-prone cannot be used in strict mode.

Some features that work in nonstrict mode will generate an error in strict mode.

We can enable strict mode in your scripts in two ways:

  • Using the -strict option with the jjs command
  • Using the "use strict" or 'use strict' directive

The following command invokes the jjs command-line tool in strict mode and tries to assign a value to undeclared variable.

C:\> jjs -strict
jjs> a = 10;
<shell>:1 ReferenceError: "a" is not defined
jjs> exit()

The following command invokes the jjs command-line tool in nonstrict mode without the -strict option.

Run the same code:

C:\> jjs
jjs> a = 10;

The following code shows how to use the use strict directive in js source file.

The directive is specified in the beginning of the script or functions.

// strict.js
"use strict"; // This is the use strict directive.
a = 10;       // This will generate an error.