Search code examples
javanashorn

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?


Solution

  • 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...