I'm wondering about something in a project of mine with OpalRB (the Ruby-to-JavaScript compiler): when you make a constant in Opal, like so:
ONE = 1
... is that essentially the same thing as saying this is JavaScript?:
const ONE = 1;
The reason that I ask this question is that the const
keyword in JS in not always properly supported in each browser and, due to that, I'm somewhat wary about using constants with Opal.
... is that essentially the same thing as saying this is JavaScript?
No it's not. const
in JavaScript makes a variable that ignores any re-assignments and keeps its original value. In Ruby, constants complain with a warning when re-assigned, but actually do get re-assigned.
Here is how ONE=1
in Ruby gets compiled by Opal:
$opal.cdecl($scope, 'ONE', 1);
As you can see, constants aren't stored as variables the way local variables are, they're stored internally inside the scope object.
The cdecl
function can do whatever it wants if ONE
is already declared. The developers of Opal however, seemed to choose to not show a warning when constants are reassigned. Try this (it's always fun to play around with this webpage and see how the compiler works).
Therefore, constants in Opal-compiled Ruby aren't.