Add More Types
Our ‘rgbToHex’ function is still declared with the keyword ‘function’. This is the JavaScript way of declaring a function, and it still leaves our function unsafe.
In JS++, it is best practice to always declare data types when possible. Since we always return a string value for our ‘rgbToHex’ function, we should restrict the return type to ‘string’.
external alert;
string rgbToHex(byte red, byte green, byte blue) {
var r = red.toString(16);
var g = green.toString(16);
var b = blue.toString(16);
while (r.length < 2) r = "0" + r;
while (g.length < 2) g = "0" + g;
while (b.length < 2) b = "0" + b;
return "#" + r + g + b;
}
alert(rgbToHex(255, 255, 255));
Now all ‘return’ statements inside the function must return an expression that evaluates to string data.
Last but not least, look at these statements:
var r = red.toString(16);
var g = green.toString(16);
var b = blue.toString(16);
What methods are being called?
Remember, a lot of programming with types in JavaScript is based on intuition. (The JS++ type system builds on top of this intuition so programming in JS++ should feel like a natural progression for JavaScript developers.) In each of the above statements, ‘toString(16)’ is being called. In other words, we know we should expect string data. Let’s change our ‘var’ to ‘string’ then:
external alert;
string rgbToHex(byte red, byte green, byte blue) {
string r = red.toString(16);
string g = green.toString(16);
string b = blue.toString(16);
while (r.length < 2) r = "0" + r;
while (g.length < 2) g = "0" + g;
while (b.length < 2) b = "0" + b;
return "#" + r + g + b;
}
alert(rgbToHex(255, 255, 255));
Compile main.jspp. Delete the rgbtohex.js JavaScript file. Edit index.html to completely remove the reference to the JavaScript rgbtohex.js file. Your index.html code should now look like this:
<!DOCTYPE html>
<head>
<title>RGB to Hex Conversion</title>
</head>
<body>
<script src="main.jspp.js"></script>
</body>
</html>
Open index.html in your web browser. You should see a message box with “#ffffff”. Congratulations! You’ve just changed a JavaScript function into JS++.