Appearance
Function Definition and Invocation
Defining Functions
In JavaScript, a function is defined as follows:
javascript
function abs(x) {
if (x >= 0) {
return x;
} else {
return -x;
}
}
The definition of the abs()
function includes:
function
indicates this is a function definition.abs
is the function name.(x)
lists the function parameters, separated by commas if multiple.{ ... }
contains the function body, which may include statements or be empty.
Note that the function terminates and returns a result upon reaching the return
statement. If no return
statement exists, it returns undefined
.
Since functions in JavaScript are also objects, the defined abs()
function is a function object, with abs
acting as a variable pointing to it.
Another way to define a function is:
javascript
let abs = function (x) {
if (x >= 0) {
return x;
} else {
return -x;
}
};
Here, function (x) { ... }
is an anonymous function with no name, but it's assigned to the variable abs
, allowing the function to be called via abs
.
These two definitions are equivalent, but the second requires a semicolon at the end.
Calling Functions
To call a function, pass the arguments in order:
javascript
abs(10); // returns 10
abs(-9); // returns 9
JavaScript allows for any number of arguments, even if they exceed the defined parameters:
javascript
abs(10, 'blablabla'); // returns 10
abs(-9, 'haha', 'hehe', null); // returns 9
If fewer arguments are passed:
javascript
abs(); // returns NaN
In this case, x
is undefined
, leading to a NaN
result. To prevent undefined
, parameter checks can be performed:
javascript
function abs(x) {
if (typeof x !== 'number') {
throw 'Not a number';
}
if (x >= 0) {
return x;
} else {
return -x;
}
}
Arguments
JavaScript provides a special keyword, arguments
, which refers to all parameters passed to the current function, resembling an array:
javascript
function foo(x) {
console.log('x = ' + x); // 10
for (let i = 0; i < arguments.length; i++) {
console.log('arg ' + i + ' = ' + arguments[i]); // 10, 20, 30
}
}
foo(10, 20, 30);
Using arguments
, you can obtain all parameters passed to the caller, even if none are defined:
javascript
function abs() {
if (arguments.length === 0) {
return 0;
}
let x = arguments[0];
return x >= 0 ? x : -x;
}
Rest Parameters
To avoid using arguments
, ES6 introduced rest parameters:
javascript
function foo(a, b, ...rest) {
console.log('a = ' + a);
console.log('b = ' + b);
console.log(rest);
}
foo(1, 2, 3, 4, 5);
// Output:
// a = 1
// b = 2
// Array [ 3, 4, 5 ]
Rest parameters must be the last parameter, gathering excess arguments into an array.
For example, you can implement a sum()
function to calculate the total of any number of arguments:
javascript
function sum(...rest) {
return rest.reduce((acc, curr) => acc + curr, 0);
}
Be Cautious with Your Return Statements
JavaScript automatically adds semicolons at the end of lines, which can lead to issues with return statements:
javascript
function foo() {
return { name: 'foo' };
}
foo(); // { name: 'foo' }
If split across lines:
javascript
function foo() {
return
{ name: 'foo' }; // returns undefined
}
Thus, the proper multi-line format is:
javascript
function foo() {
return { // No automatic semicolon added
name: 'foo'
};
}
Exercise
Define a function area_of_circle()
that calculates the area of a circle with two parameters:
r
: the radius of the circlepi
: the value of π, defaulting to 3.14 if not provided
javascript
function area_of_circle(r, pi = 3.14) {
return pi * r * r;
}
// Tests:
if (area_of_circle(2) === 12.56 && area_of_circle(2, 3.1416) === 12.5664) {
console.log('Test passed');
} else {
console.log('Test failed');
}
Help Xiaoming Fix His max() Function
Xiaoming wrote a max()
function that always returns undefined
due to improper line breaks in return statements:
javascript
function max(a, b) {
if (a > b) {
return
a; // Fix: remove line break
} else {
return
b; // Fix: remove line break
}
}
console.log(max(15, 20));
To fix this, remove the line breaks after return
.