I've been programming for the Web for quite some time now, but have only just recently discovered a few new intricacies regarding the use of functions and the weird (or so I view them as) things you can do with them. However, they seem at this point only to be syntactically pretty things. I was hoping somebody might enlighten me as to how some of these newly discovered aspects could prove to be useful.
For example, the first time I ran this, I thought for sure it would not work:
<script>
function x(q)
{
q(x);
}
x(function(a)
{
alert(a);
}
);
</script>
But it did! Somehow, creating a named function which receives a different, anonymous function as its only parameter and then runs the function passed to it with itself passed as the parameter to it works just fine. This positively blew my mind and I'm almost certain there's a vast amount of practicality to it, but I just can't quite place it yet.
Ah, and another thing I was elated to discover: using a globally scoped variable to store a function, one can later in the execution use JavaScript's eval() function to modify that variable, thus changing the function's inner workings dynamically. An example:
<script>
var f = function()
{
alert('old text');
}
eval('f = ' + f.toString().replace('old text', 'new text'));
f();
</script>
Sure enough, that code alerts the "new text" string; when I saw that, my mind was once again blown, but also immediately intrigued as to the potential to create something incredible.
So... my burning question for Stack Overflow: how can such seemingly abstract coding principles be used in any positive way?