#JavaScript
#Declare and call javascript/function/function
declare a function
1.
function functionName( argument1, argument2, ... ) {
// Do Something
}
2.
var functionName = function( argument1, argument2, ... ) {
// Do Something
};
call a function
functionName( value1, value2, ... );
If you declare a function with Method 1, the function call can be made before the function declaration or after the function declaration.
functionName( value1, value2, ... );
function functionName( argument1, argument2, ... ) {
// Do Something
}
function functionName( argument1, argument2, ... ) {
// Do Something
}
functionName( value1, value2, ... );
If you declare a function with Method 2, the function call must come after the function declaration.
var functionName = function( argument1, argument2, ... ) {
// Do Something
};
functionName( value1, value2, ... );
example 1
This is an example of outputting Hello World! Declare and call the function in method 1.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>
<body>
<script>
function jbFunction() {
document.write( '<p>Hello World!</p>' );
}
jbFunction();
</script>
</body>
</html>
example 2
This is an example of outputting Hello World! Declare and call the function in method 2.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>
<body>
<script>
var jbFunction = function() {
document.write( '<p>Hello World!</p>' );
};
jbFunction();
</script>
</body>
</html>
example 3
Here is an example of a function that takes arguments.
If the number of arguments is the same as the number of values, it prints without any problems.
Arguments without values return undefined if there are fewer values than arguments.
If there are more values than arguments, the more values than arguments are ignored.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
<style>
h1 {
font-family: Consolas;
}
h1 span {
color: #2196f3;
}
</style>
</head>
<body>
<script>
function jbFunction( jbName, jbJob ) {
document.write( '<h1>My name is <span>' + jbName + '</span>. I am a <span>' + jbJob + '</span>.</h1>' );
}
jbFunction( 'John', 'student' );
jbFunction( 'John' );
jbFunction( 'John', 'student', 'male' );
</script>
</body>
</html>