News & UpdatesProgrammingWeb programming Store My Projects
Links
Affiliates

JavaScript Tutorial – 08 – Functions

JavaScript tutorials

A function is a reusable code block that will execute only when it’s called. They are normally placed in the head section of the document, because this assures that the browser loads them before they’re used.

Defining functions

To create a function the function keyword is used followed by a name, an optional parameter list, and a code block.

function myFunc() 
{ 
  document.write("Hello World"); 
}

Calling functions

Calling the function is done by using the function’s name followed by a set of parenthesis in the body section of the document.

myFunc();

Parameters

The parenthesis can be used to pass parameters to the function in the form of a comma separated list.

function myFunc(x,y) 
{ 
  document.write(x + y); 
}    
myFunc("Hello", " World");

JavaScript will not complain if too few parameters are sent. The unspecified parameters will simply become undefined. Same thing if too many parameters are passed, there will be no errors. JavaScript even provides a way to access such parameters using the arguments array. This array is a built-in part of the function object and contains all arguments passed to the function.

function myFunc() 
{ 
  for (var i = 0; i < arguments.length; i++) 	 
    document.write(arguments[i]);
}

Return statement

The return keyword causes a function to exit.

function myFunc(x,y) 
{ 
  return; // exit function
}

It can optionally be given a value to return and will then make calls to that function evaluate to that value.

function myFunc(x,y) 
{ 
  return x + y; // exit function and return value
}  
document.write(myFunc("Hello", " World");

Anonymous functions

There is a second notation for creating functions, the so called anonymous function. An anonymous function is declared using the Function constructor. Each parameter in the constructor is included as a string value separated by commas and the last parameter string consists of the function statements.

var myFunc = new Function("x","y", "document.write(x+y);");
Recommended additional reading:
Sams - Teach Yourself JavaScript in 24 Hours