Defined Functions
In JavaScript, define the following functions:
function abs(x) { if (x >= 0) { return x; } else { return -x; } }
Above abs()
function is as follows:
function
He pointed out that this is a function definition;abs
Is the name of the function;(x)
Lists the parameters of the function, the plurality of parameters within the parentheses in,
the partition;{ ... }
Code between the body of the function, may comprise several statements, or even without any statement.
Please note that statements inside the function body at the time of execution, if implemented to return
the time, the function completes and returns the results. Thus, the internal function is determined by the conditions and the cycle can achieve very complex logic.
If there is no return
statement after the completion of function execution will return results, but the result is undefined
.
The second way defined functions
Since the function of JavaScript is an object , as defined above abs()
function is actually a function object , and function names abs
can be regarded as variable to point to the function.
Thus, the second function is defined as follows:
var abs = function (x) { if (x >= 0) { return x; } else { return -x; } };
In this way, function (x) { ... }
it is an anonymous function, it has no function name. However, this anonymous function assigned to the variableabs
, so, by the variable abs
you can call the function.
Above two definitions fully equivalent , attention to the second way in accordance with the complete syntax need to add at the end of a function body ;
, indicating the end of an assignment statement.
call function
When you call the function, passing parameters in order to:
ABS (10); // Returns 10 ABS (-9); // Returns 9
Since JavaScript allows you to pass arbitrary parameters without affecting the call, so the incoming parameters defined by many parameters than there is no problem, although the internal functions do not require these parameters:
ABS (10, 'blablabla'); // Returns 10 ABS (-9, 'haha', 'Hehe', null ); // Returns 9
Incoming less than the defined parameters is not a problem:
ABS (); // returns NaN
At this time, abs(x)
parameters of the function x
will receive undefined
, as a calculation result NaN
.
To avoid receiving undefined
, you can check the parameters: