Skip to main content
1-Visitor
May 19, 2020
Solved

Variables declared with const are not block-scoped

  • May 19, 2020
  • 1 reply
  • 1290 views

In ThingWorx 8.5.2-b90, variables declared with let are block-scoped, however, variables declared with const are not block-scoped.

 

Related section of the specification: https://tc39.es/ecma262/#sec-let-and-const-declarations

 

The let and const constructs were introduced in ES6. This article states that ThingWorx 8.5 supports ES6: https://community.ptc.com/t5/IoT-Tech-Tips/Arrow-functions-filter-map-amp-reduce-ThingWorx-8-5-supports-ES6/td-p/630164

 

Related post: https://community.ptc.com/t5/ThingWorx-Developers/Incorrect-work-of-const-inside-while-loop/m-p/663884

 

Related open issue on github: https://github.com/mozilla/rhino/issues/326

 

The following code snippet can be used to reproduce the issue:

  • test1a - no error using let
  • test1b - error thrown using const
  • test2a - no error using let
  • test2b is commented because it fails syntax checking

 

 

(function test1a() {
 var seen = {};
 var arr = ['a', 'b'];

 for (var i = 0; i < arr.length; i++) {
 let item = arr[i];
 if (seen[item]) {
 throw new Error('test1a: already seen: ' + item);
 } else {
 seen[item] = true;
 }
 }
})();

(function test1b() {
 // Same as test1a except variable `item` is declared using `const` instead of `let`
 var seen = {};
 var arr = ['a', 'b'];

 for (var i = 0; i < arr.length; i++) {
 const item = arr[i];
 if (seen[item]) {
 throw new Error('test1b: already seen: ' + item);
 } else {
 seen[item] = true;
 }
 }
})();

(function test2a() {
 {
 let a = 'a';
 if (a !== 'a') {
 throw new Error('test2a: a !== \'a\'');
 }
 }

 {
 let a = 'b';
 if (a !== 'b') {
 throw new Error('test2a: a !== \'b\'');
 }
 }
})();

//(function test2b() {
// // Same as test2a except variable `a` is declared using `const` instead of `let`
// {
// const a = 'a';
// if (a !== 'a') {
// throw new Error('test2b: a !== \'a\'');
// }
// }
//
// {
// const a = 'b';
// if (a !== 'b') {
// throw new Error('test2b: a !== \'b\'');
// }
// }
//})();

 

 

Is this fixed in a later version of ThingWorx?

Best answer by Constantine

Hello,

 

The quick answer is "no": https://github.com/mozilla/rhino/issues/326

 

...unless PTC decides to switch away from Rhino, which I don't believe they have announced yet.

 

Regards,
Constantine

1 reply

18-Opal
May 20, 2020

Hello,

 

The quick answer is "no": https://github.com/mozilla/rhino/issues/326

 

...unless PTC decides to switch away from Rhino, which I don't believe they have announced yet.

 

Regards,
Constantine