Updated on Kisan Patel
JavaScript functions provide a way to encapsulate a block of code in order to reuse the code several times.
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function created using the function statement and syntax similar to the following.
function functionName(parameters) { code to be executed }
Create a simple, named, parameter-less function using the function statement.
function simpleFunction() { alert("Hello from function!"); }; simpleFunction();
A function created using the function keyword and given a name is known as both a declarative function and a static function.
Provide arguments for the incoming data, and return the result.
function makeHello(strName) { return ("Hello " + strName); } window.onload=function() { var name = prompt("What's your name?",""); var result = makeHello(name); alert(result); }
Function arguments are a way to pass data to a function. The arguments are separated by commas and included in the parentheses following the function name.
makeHello(firstName, lastName);
The function then processes the arguments, as needed.
function makeHello(firstName, lastName) { alert("Hello " + firstName + " " + lastName); }
Data is returned from the function to the calling program using the return statement.
function makeHello(firstName, lastName) { return "Hello " + firstName + " " + lastName; }
You can pass several arguments to the function, but only one return value.
Passing Objects as argument to a Function
You can use objects, such as arrays, as function arguments.
function makeHello(name) { name[name.length] = "Hello " + name[0] + " " + name[1]; } var name = new Array('from','Function'); makeHello(name); alert(name[2]); // displays "Hello from Function"