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
}
{ 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>
<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 (,)
Declare the argument, as variables, when you declare the function:
The variables and the arguments must be in the expected order. The first
variable is given the value of the first passed argument etc.
These arguments can be used inside the function.
You can send as many arguments as you like, separated by commas (,)
myFunction(argument1,argument2)
function myFunction(var1,var2)
{ some code
}
{ some code
}
Example
<button
onclick="myFunction('Harry Potter','Wizard')">Try
it</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
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>
<button onclick="myFunction('Bob','Builder')">Try it</button>
No comments: