compuhelpindia.com

JavaScript Function

Compuhelpindia.com
« Previous                                                                                                                                       Next Chapter »


A function is a block of code that will be executed when "someone" calls it:
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
 
JavaScript Function Syntax
A function is written as a code block (inside curly { } braces).
Eaxmple:
function functionname()
{
some code to be executed
}
 
Calling a Function with Arguments:
When you call a function, you can pass along some values to it, these values are called arguments or parameters.
These arguments can be used inside the function.
Example:
myFunction(arg1,arg2)
 
Declare the argument, as variables, when you declare the function:
function myFunction(var1,var2)
{
some code
}
 
Example:
<button onclick="myFunction('Compuhelp','Chandigarh')">Try it</button>
<script>
function myFunction(Compuhelp,job)
{
alert("Welcome " + Compuhelp + ", the " + Chandigarh);
}
</script>
The function above will alert "Welcome Compuhelp, the Chandigarh" when the button is click.
Example:
<!DOCTYPE html>
<html>
<body>
<p>Click one of the buttons to call a function with arguments</p>

<button onclick="myFunction('Compuhelp','Chandigarh')">Click for Compuhelp</button>
<button onclick="myFunction('Java','Script')">Click for JavaScript</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>

</body>
</html>

</pre>
<button onclick="myFunction('Compuhelp','Chandigarh')">Try it</button>

<script>
function myFunction(Compuhelp,job)
{
alert("Welcome " + Compuhelp  + job);
}
</script>

Click one of the buttons to call a function with arguments