Pages

JavaScript Functions


A function is a block of code that will be executed when "someone" calls it:


JavaScript Function Syntax

A function is written as a code block (inside curly { } braces), preceded by the function keyword:
function functionname()
{
some code to be executed
}
 

Example

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}

</script>
</head>

<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
 
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.
You can send as many arguments as you like, separated by commas (,)
myFunction(argument1,argument2)
Declare the argument, as variables, when you declare the function: 

function myFunction(var1,var2)
{
some code
}
The variables and the arguments must be in the expected order. The first variable is given the value of the first passed argument etc.

Example

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
 
 The function above will alert "Welcome Harry Potter, the Wizard" when the button is clicked.
The function is flexible, you can call the function using different arguments, and different welcome messages will be given:

Example

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<button onclick="myFunction('Bob','Builder')">Try it</button>
 
 
 

No comments:

Flag Counter
| Copyright © 2013 Remote Tutor