JavaScript definition function
Define function
In JavaScript, the way to define a function is as follows:
function abs(x) { if (x >= 0) { return x; } else { return -x; } }
The definition of the above abs() function is as follows:
function indicates that this is a function definition;
abs is the name of the function;
(x)The parameters of the function are listed in brackets, and multiple parameters are separated by,; the code between
{ ... } is the function body, which can contain several statements. There can even be no statement at all.
Please note that when the statements inside the function body are executed, once return is executed, the function will be executed and the result will be returned. Therefore, very complex logic can be implemented inside the function through conditional judgment and looping.
If there is no return statement, the result will be returned after the function is executed, but the result will be undefined.
Since a JavaScript function is also an object, the abs() function defined above is actually a function object, and the function name abs can be regarded as a variable pointing to the function.
So, the second way of defining a function is as follows:
var abs = function (x) { if (x >= 0) { return x; } else { return -x; } };
In this way, function (x) { ... } is an anonymous function, it has no function name. However, this anonymous function is assigned to the variable abs, so the function can be called through the variable abs.
The above two definitions are completely equivalent. Note that the second method requires adding a ; at the end of the function body according to the complete syntax, indicating the end of the assignment statement.
We complete the function of summing two numbers and displaying the result. And give the function a meaningful name: "add2", the code is as follows:
<!DOCTYPE html> <html> <body> <script type="text/javascript"> function add2(){ sum = 3 + 2; alert(sum); } add2(); </script> </body> </html>
Result: