nashorn - How to avoid "ReferenceError: "a" is not defined" -
the below code throws referenceerror: "a" not defined. possible avoid , treat variable null?
scriptengine engine = new scriptenginemanager().getenginebyname("nashorn"); map<string, string> s = new hashmap<string, string>(); // s.put("a", "a"); bindings bindings = engine.createbindings(); bindings.putall(s); object res = engine.eval("!a", bindings); system.out.println(res);
if don't have variable name "a" defined in scope chain, referenceerror should thrown per ecmascript specification. if uncomment line:
// s.put("a", "a");
line "a" defined , therefore no referenceerror.
you can check if variable defined or not using "typeof" operator. "typeof == 'undefined'" evaluate false undefined variable "a". won't referenceerror undefined variables. again standard compliant behavior.