Functions in parentheses

brettz9brettz9 BeginnerLink Clerk
Hello,

I am new to Javascript, so please bear with me.

I was examining the bookmarklet "Sort Tables" here and it contained a function ITSELF enclosed in pareentheses:
(function(){
	var j, thead;
	for(j=0;j<g_tables.length;++j){
		thead=g_tables[j].createTHead();
		insAtTop(thead, makeHeader(j,countCols(g_tables[j])))
	}
	}) ();

As this script did not work with the parentheses removed, I am wondering what this does. Please note: I am referring to the function declaration being itself enclosed not the arguments passed to it.

thanks,
Brett

Comments

  • ChroderChroder Senior Member The Royal RAM
    In this case, the function is a closure (aka 'inline function' aka 'anonymous function').

    A function in Javascript is just another type of value. The parenthesis just make the function act as a value, which is then executed (as per the familiar '()' at the end).

    For example, you could assign a function to a variable and then call it:
    myFunc = function() { .... code .... };
    myFunc();
    
    Or just stick parenthesis around it and execute it as an inline "value":
    (function() { .... code ....})();
    
  • brettz9brettz9 Beginner Link Clerk
    Wonderful, thanks!

    I had seen online information about anonymous functions, but I hadn't seen them with outer parentheses...What you said makes sense...

    It threw me off because it wasn't an argument to another function.

    best wishes,
    Brett
Sign In or Register to comment.