Bug with "let" variable in for loop: ReferenceError: "obj" is not defined
Anton Mitrofanov
mitrofanov at krista.ru
Fri Apr 26 13:42:12 UTC 2024
Hi.
We have some code like this:
let System = Java.type('java.lang.System');
let ArrayList = Java.type('java.util.ArrayList');
function test(array) {
let list = new ArrayList();
for each (let obj in array) {
let found = list.stream().filter(function(o) {
return o == obj;
}).findFirst().orElse(null);
if (found) continue;
list.add(obj);
}
return list;
}
let res = test(['test1', 'test2', 'test1', 'test3']);
System.out.println(res.size());
The expected result of which is: 3
But with Java 17 and Nashorn 15.4 the result is an exception:
<eval>:8 ReferenceError: "obj" is not defined
Caused by: <eval>:8 ReferenceError: "obj" is not defined
at org.openjdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
at org.openjdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:318)
at org.openjdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:290)
at org.openjdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:277)
at org.openjdk.nashorn.internal.runtime.AccessorProperty.checkUndeclared(AccessorProperty.java:570)
at org.openjdk.nashorn.internal.runtime.AccessorProperty.getGetter(AccessorProperty.java:505)
at org.openjdk.nashorn.internal.runtime.FindProperty.getGetter(FindProperty.java:91)
at org.openjdk.nashorn.internal.runtime.ScriptObject.findGetMethod(ScriptObject.java:1997)
at org.openjdk.nashorn.internal.runtime.ScriptObject.lookup(ScriptObject.java:1867)
If you change the "let" declaration to "var", then everything is fine.
If you leave "let" in the code and change "if (found)" to "if (true)", then the exception becomes different:
Caused by: java.lang.NullPointerException: Cannot invoke "org.openjdk.nashorn.internal.codegen.Label$Stack.push(org.openjdk.nashorn.internal.codegen.types.Type)" because "this.stack" is null
at org.openjdk.nashorn.internal.codegen.MethodEmitter.pushType(MethodEmitter.java:250)
at org.openjdk.nashorn.internal.codegen.MethodEmitter._new(MethodEmitter.java:359)
at org.openjdk.nashorn.internal.codegen.MethodEmitter._new(MethodEmitter.java:372)
at org.openjdk.nashorn.internal.codegen.FieldObjectCreator.createForInIterationScope(FieldObjectCreator.java:133)
at org.openjdk.nashorn.internal.codegen.CodeGenerator.enterForIn(CodeGenerator.java:1817)
But the expected result is the same as with "var": 0
P.S. I apologize for writing directly to ML and not to the issue tracker, but I couldn’t find my bug there and create a new one.
More information about the nashorn-dev
mailing list