Anonymous Function Examples in Javascript

Learning javascript by copying and pasting useful snippets off the web, the only aspects of Javascript that I’ve ever looked closely at were to change css properties, validate forms, or get some values with ajax. Because of this, there is stillĀ  a large portion of the language that I’m still learning. I’ve never used anonymous functions in any language, but they’ve always looked like an interesting concept, so I decided to give it a shot. This is what I learned with a few short examples.

This little javascript feature can be hugely useful for passing functions as variables or declaring quick functions inline for the programmer who is to lazy to switch files or scroll to wherever that annoying javascript declaration is.

To pass a function as a variable either with a reference or inline:

<script type=’text/javascript’>

//garbage example data
var array = [ 3, 14, 15, 9, 26 ]
var array2 = [ 3, 14, 15, 9, 26 ]

//This function takes an array and a function as parameters.
//It then executes the passed function on every element of the array.
function execute_on_array( array_of_stuff, anonymous_function )
{
    for (var i=0; i<array_of_stuff.length; i++)
    {
        alert(“before ” + array_of_stuff[i]);
        array_of_stuff[i] = anonymous_function(array_of_stuff[i]);
        alert(“after” + array_of_stuff[i]);
    }
}

//Here’s the anonymous function that is now referred to as nullify_function
var nullify_function = function (x) { if(x) return 0; else return x; }

//Passing an anonymous function in as a variable
execute_on_array( array_of_numbers, nullify_function);

//Here is the call to the previous function with an anonymous function defined inline
function execute_on_array( array2, function (x) { x=0; return x; } );

</script>

I could see how this would make recursion in javascript really easy.

Share

Comments are closed.