Javascript basic tutorial function
Javascript What is a function?
A function is a set of statements that perform a specific function. Without functions, it might take five, ten, or more lines of code to complete the task. At this time, we can put the code block that performs a specific function into a function and call this function directly, saving the trouble of repeatedly entering a large amount of code.
How to define a function
function function name(){
Function code segment;
}
Note:
#1. function is the keyword that defines the function.
2. "Function name" is the name you give the function.
3. Replace "function code" with a code that completes a specific function
Let's write an example below, the following code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>函数</title> <script type="text/javascript"> function sum(){ var a=10; var b=5; var c= a+b; document.write(c); } </script> </head> <body> </body> </html>
As with the above code, we write functions one by one , the function of the function is to find the sum of a+b. Now how do we use the function?
How to call the function
Syntax: function name();
So in the example we wrote above, how should we output the function, as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>函数</title> <script type="text/javascript"> function sum(){ var a=10; var b=5; var c= a+b; document.write(c); } sum(); </script> </head> <body> </body> </html>
In this way we can call the function, and the output result is 15;