5

I just stumbled upon a strange JavaScript error using Mozilla Rhino as a JavaScript engine.

This one line script throws an error:

eval("const a = 5;");

The error is:

TypeError: redeclaration of var a.

I would expect this error, if the line is execute multiple times - but it is only executed once, as this one line is the whole program.

Can anyone explain, why this error occurs?

chriz
  • 198
  • 1
  • 5
  • Odds are one of the other scripts you're including already declared a constant named `a`. Try removing scripts (particularly 3rd party if you know you didn't) from the head one by one until this error doesn't appear – Nick Aug 21 '12 at 14:53
  • How do you execute the JS with Rhino? – Bergi Aug 21 '12 at 14:54
  • I executed it within Eclipse - there are no other scripts included. I suspect it is an error within Rhino, as it works with Chrome. – chriz Aug 21 '12 at 14:59
  • 1
    @ user1407611 try to verify its usage.. if (typeof(a) == "undefined") {....} – Scorpio Aug 21 '12 at 15:10
  • Make sure that there are no other variable `a` in the same scope. – Diode Aug 21 '12 at 15:54
  • 1
    I can't reproduce the error in the Firefox console. `eval("const a = 5; a");` logs `5`. – Peter Olson Aug 21 '12 at 16:01
  • I also cannot reproduce it with Chrome - I filed a bug against Rhino – chriz Aug 21 '12 at 16:09

1 Answers1

-3

There is no const type in javascript. You will have to use this instead

eval("var a = 5;");

zon7
  • 529
  • 3
  • 12
  • 1
    Actually, there is, see: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/const – chriz Aug 21 '12 at 15:03
  • Yes, but its not totally standard, as you can read in your page "The current implementation of const is a Mozilla-specific extension". Yes, it works in chrome but... – zon7 Aug 21 '12 at 15:04
  • That's right - however, it works if I move it out of the eval(), I just fails within eval() – chriz Aug 21 '12 at 15:05
  • Then try using the var type instead of the const. Maybe const is not implemented to the core. – zon7 Aug 21 '12 at 15:10
  • 1
    @zon7 He did that in Rhino, which is Mozilla's JS engine. He's not looking for crossbrowser solution, but for the explanation of the error. – Imp Aug 21 '12 at 15:10
  • Seems so, I think I will file a bug against Rhino, it works in Chrome and so it should in Rhino. – chriz Aug 21 '12 at 15:12