logo

NJP

Deep Dive: JavaScript Inner Functions...

Import · Feb 09, 2010 · article

imageHere'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:

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); } }

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.

View original source

https://www.servicenow.com/community/in-other-news/deep-dive-javascript-inner-functions/ba-p/2288160