How to use More Safely In JS++
You can use JavaScript more safely from JS++ than you can from JavaScript itself.
Let’s start by modifying our main.jspp code to explicitly use the ‘byte’ data type:
external alert;
external rgbToHex;
byte red = 255;
byte green = 255;
byte blue = 255;
alert(rgbToHex(red, green, blue));
Compile main.jspp and open index.html. The result should be exactly the same: a message box will pop up containing “#ffffff”. However, there’s a difference this time: you’re guaranteed to only be able to send whole number values ranging from 0 to 255.
Remember all those checks in the JavaScript function to make sure we received acceptable RGB input values? If incorrect values were provided, the script will stop application execution by throwing exceptions. All of these potential errors have been wiped out by using JS++ and declaring types. These errors have been wiped out despite the fact that we haven’t modified any of the original JavaScript code. The runtime errors are still present in the JavaScript code, but they will never execute because the input values we provide will always be correct.
Try changing one of the ‘red’, ‘green’, or ‘blue’ variables to a number outside the 0 to 255 range:
external alert;
external rgbToHex;
byte red = -1;
byte green = 255;
byte blue = 255;
alert(rgbToHex(red, green, blue));
Now try to compile the modified main.jspp file. You’ll get an error:
[ ERROR ] JSPPE5013: Computed value `-1' is out of range for type `byte' at line 4 char 11 at main.jspp
We can build on this and re-write the entire ‘rgbToHex’ function in JS++ instead of JavaScript to improve type safety while removing all the runtime checks and errors.