SlightlyLoony
Tera Contributor

find_real_file.pngHere's a simple and very useful feature of JavaScript that you may not be aware of: functions may be nested, one inside another. Here's a simple example, in a script you can run on your instance:

<div>
gs.log('Hex value of 11259375 is: ' + hex(11259375));

function hex(value) {
var rem = value;
var result = '';
while (rem > 0) {
var r = rem % 16;
rem = Math.floor(rem/16);
result = hexChar(r) + result;
}
return result;

function hexChar(charValue) {
return '0123456789ABCDEF'.charAt(charValue & 0xFF);
}
}</div>


Note that the function hexChar is entirely within the function hex.

You might say: "Ok, but why on earth would I ever want to do this?" Fair question. There are at least two good reasons that I can think of: (1) you have some code that will be used repeatedly in the outer function, and which isn't useful outside that function, and (2) you can break up a large function into smaller, easier to understand (and maintain) pieces.

1 Comment