Java Language Nashorn JavaScript engine Usage of Java objects in JavaScript in Nashorn

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

It's possible to pass Java objects to Nashorn engine to be processed in Java code. At the same time, there are some JavaScript (and Nashorn) specific constructions, and it's not always clear how they work with java objects.

Below there is a table which describes behaviour of native Java objects inside JavaScript constructions.

Tested constructions:

  1. Expression in if clause. In JS expression in if clause doesn't have to be boolean unlike Java. It's evaluated as false for so called falsy values (null, undefined, 0, empty strings etc)
  2. for each statement Nashorn has a special kind of loop - for each - which can iterate over different JS and Java object.
  3. Getting object size. In JS objects have a property length, which returns size of an array or a string.

Results:

TypeIffor each.length
Java nullfalseNo iterationsException
Java empty stringfalseNo iterations0
Java stringtrueIterates over string charactersLength of the string
Java Integer/Longvalue != 0No iterationsundefined
Java ArrayListtrueIterates over elementsLength of the list
Java HashMaptrueIterates over valuesnull
Java HashSettrueIterates over itemsundefined

Recommendatons:

  • It's advisable to use if (some_string) to check if a string is not null and not empty
  • for each can be safely used to iterate over any collection, and it doesn't raise exceptions if the collection is not iterable, null or undefined
  • Before getting length of an object it must be checked for null or undefined (the same is true for any attempt of calling a method or getting a property of Java object)


Got any Java Language Question?