Difference between null and undefined in Nashorn

I run 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 we get m == null and m1 == null.

How to determine if a value is undefined or null?

+6
source share
3 answers

Java does not have the concept of "undefined", so to understand the difference, you will need to express it in script language. I suggest using this expression:

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

I would check

 engine.eval("typeof out") 

which will be "undefined" and

 engine.eval("typeof out1") 

will be an "object"

+4
source

Actually, the correct way to find out if the object returned by the script is undefined is a ScriptObjectMirror request:

 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's internal API

You can also do this 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"); } 

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

+4
source

Source: https://habr.com/ru/post/984267/


All Articles