Sergey  Eliseev
Sergey Eliseev

Reputation: 93

Differ null and undefined values in Nashorn

I'm running this code

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("var out;");
engine.eval("var out1 = null;");
Object m = engine.get("out");
Object m1 = engine.get("out1");

And getting m == null and m1 == null.

How to determine if value is undefined or null?

Upvotes: 7

Views: 5011

Answers (3)

Renato
Renato

Reputation: 13690

Actually, the correct way to know if the Object returned by the script is undefined is by asking ScriptObjectMirror:

import jdk.nashorn.api.scripting.ScriptObjectMirror;

Object m = engine.get("out");

if (ScriptObjectMirror.isUndefined(m)) {
    System.out.println("m is undefined");
}    

Alternative way, using Nashorn internal API

You can also do it by checking its type:

import jdk.nashorn.internal.runtime.Undefined;

Object m = engine.get("out");

if (m instanceof Undefined) {
    System.out.println("m is undefined");
}

Notice that Nashorn did not make the Undefined type part of the public API, so using it can be problematic (they are free to change this between releases), so use ScriptObjectMirror instead. Just added this here as a curiosity...

Upvotes: 6

A. Sundararajan
A. Sundararajan

Reputation: 4405

I'd check

engine.eval("typeof out") 

which will be "undefined" and

engine.eval("typeof out1") 

would be "object"

Upvotes: 4

Java doesn't have a concept of "undefined", so understanding the distinction will require expressing it in the script's language. I suggest using this expression:

Boolean isUndefined = engine.eval("out === undefined");

Upvotes: 4

Related Questions