Javascript Function

A javascript function is a group of statements that is used for performing a specific task. We can invoke it from anywhere in our program. It provides the facility of code re-usability.

Syntax:

function functionname(parameterList) {
         //Block of statements
      }

JavaScript Function Object:

For the global execution of a piece of code, a new Function object can be created with the help of a Function Constructor in Javascript.

Syntax:

new Function (parameters)
{
    code to be executed;
}

JavaScript Function Methods:

apply() method:
Use: To call a function containing this value and a single array of arguments.

bind() method:
Use: To create a new function.

call() method:
Use: To call a function containing this value and an argument list.

toString() method:
Use: To return the result in the form of a string.

JavaScript function example:
<html>
<head>
<script type="text/javascript">
function sayHello(){
alert("Hello w3schools.com");
}
</script>
</head>
<body>
<p>Hello World Javascript Example.</p>
<form>
<input type="button" value="Say Hello" onclick="sayHello()"/>
</form>
</body>
</html>
JavaScript function with arguments example:
<html>
<head>
<script type="text/javascript">
function sayHello(msg){
alert(msg);
}
</script>
</head>
<body>
<p>Hello World Javascript Example.</p>
<form>
<input type="button" value="Say Hello"
onclick="sayHello('Hello w3schools.com')"/>
</form>
</body>
</html>
JavaScript function return value example:
<html>
<head>
<script type="text/javascript">
function sayHello(msg){
alert(getMsg());
}
function getMsg(){
return "Hello w3schools.com";
}
</script>
</head>
<body>
<p>Hello World Javascript Example.</p>
<form>
<input type="button" value="Say Hello" onclick="sayHello()"/>
</form>
</body>
</html>