Syntactic extensions

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. Example:

function sqr(x) x*x

// is equivalent to
// function sqr(x) { return x*x }

For each expressions

This is another Mozilla JavaScript 1.6 extension supported by Nashorn. ECMAScript for..in iterates over property names or array indices of an object. for..each..in loop iterates over property values of an object rather than property names/indices.

 

for each (variable in object) { statement }

// print each array element 
var arr = [ "hello", "world" ];
for each (a in arr) {
 print(a)
}

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:

// This syntax is primarily used to support anonymous class-like syntax for
// Java interface implementation as shown below.

var r = new java.lang.Runnable() {
    run: function() { print("run"); }
}

 

Anonymous function statements

Top-level function statements can be anonymous. Example:

 

function () {
    print("hello")
}

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:

var str = <<EOF

This is a string that contains multiple lines
hello
world
That's all!

EOF

print(str)

 

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.

var x = "World"
var str = "Hello, ${x}"

print(str) // prints "Hello, World" because ${x} is substituted with value of variable "x"

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.

// exec "ls -l" to get file listing as a string
var files = `ls -l`
var lines = files.split("\n");

// print only the directories
for (var l in lines) {
    var line = lines[l];
    if (line.startsWith("d")) // directory
        print(line)
}