Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differ null and undefined values in Nashorn

Tags:

java

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?

like image 260
Sergey Eliseev Avatar asked Mar 26 '15 11:03

Sergey Eliseev


People also ask

What is the difference between null and undefined values?

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.

What is the difference between undefined and null value in JavaScript?

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.

Why does js have null and undefined?

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

Why nashorn is deprecated?

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.


1 Answers

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

like image 128
Renato Avatar answered Oct 01 '22 11:10

Renato