Search code examples
nashorn

nashorn - How to avoid "ReferenceError: "a" is not defined"


The below code throws ReferenceError: "a" is not defined. Is it possible to avoid it and treat the variable as 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);

Solution

  • If you don't have any variable by the name "a" defined in your scope chain, then ReferenceError should be thrown as per the ECMAScript specification. If you uncomment this line:

    //        s.put("a", "a");
    

    line then "a" is defined and therefore no ReferenceError.

    You can check if a variable is defined or not using the "typeof" operator. "typeof a == 'undefined'" will evaluate to false for undefined variable "a". You won't get ReferenceError for undefined variables. Again this is standard compliant behavior.