Community Tip - You can Bookmark boards, posts or articles that you'd like to access again easily! X
Hello!
May I ask why constants work in ThingWorx differently than in normal JavaScript?
Example:
let i = 5;
while (i > 0) {
const a = i;
logger.warn(a);
i--;
}
In log we will see:
5
5
5
5
5
In any normal JS code runner such as Codepen we will see in console log:
5
4
3
2
1
As far as I understand, such a script execution violates the basic ideology of constants in JavaScript - 'const' is initialized and exists only in the block (loop) scope.
The same behaviour in 'for' loop. 'const' works correctly only in functions like 'map', 'forEach'.
Thank you in advance.
Solved! Go to Solution.
ThingWorx uses Rhino JavaScript engine. So, if you try to execute your code here, you will get the same output as ThingWorx.
Further, I was just wondering, isn't the TWX implementation better since the idea of const is that, once defined, it should not be possible to reassign its value?
ThingWorx uses Rhino JavaScript engine. So, if you try to execute your code here, you will get the same output as ThingWorx.
Further, I was just wondering, isn't the TWX implementation better since the idea of const is that, once defined, it should not be possible to reassign its value?
thank you for your answer.
No, I don't think, that this realisation is better, moreover, I think it is erroneous.
'const' cannot be reassign in scope - and this make sense: I want to be sure, that inside my loop scope for each iteration variable 'a' will be not reassign. But I cannot be sure, because I have to use 'let' instead 'const' in TW!
The problem lies deeper: it turns out that in the context of the Rhino JavaScript engine, a loop scope is not a closure for each iteration, but a common context for any iteration.
Hi @lala_guliyeva.
Unfortunately, this is a known bug in the Rhino JavaScript implementation: https://github.com/mozilla/rhino/issues/326
Therefore, the fix will have to come from Rhino.
Regards.
--Sharon
Hi @lala_guliyeva.
If you feel your question has been answered, please mark the appropriate response as the Accepted Solution for the benefit of others with the same question.
Thank you for your participation in our community!
Regards.
--Sharon