cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Community Tip - Need to share some code when posting a question or reply? Make sure to use the "Insert code sample" menu option. Learn more! X

Incorrect work of 'const' inside while loop

lala_guliyeva
11-Garnet

Incorrect work of 'const' inside while loop

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.

ACCEPTED SOLUTION

Accepted Solutions

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?

View solution in original post

4 REPLIES 4

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

slangley
23-Emerald II
(To:slangley)

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

Announcements


Top Tags