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?
Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript. Undefined: It means the value does not exist in the compiler. It is the global object.
Difference Between undefined and nullundefined is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything. null is a variable that is defined but is missing a value.
Undefined is supposed to mean a variable has no value (or a property does not exist) because the programmer has not yet assigned it a value (or created the property). Null is supposed to signal that a variable has no value because the programmer purposefully cleared the value and set it to `null`.
With the release of Java 11, Nashorn was deprecated citing challenges to maintenance, and has been removed from JDK 15 onwards. Nashorn development continues on GitHub as a standalone OpenJDK project and the separate release can be used in Java project from Java 11 and up.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With