In this article, you’ll focus on defining your own custom functions in JavaScript, explaining how functions are defined, declared, scoped, and parameter definitions.

The function definitions

A function can be thought of as a piece of code wrapped in a variable that allows calling that code to be reused over and over again. In this article, I’ll discuss three different ways to define functions in JavaScript.

The first way is to define a function as a value and assign that value to a variable (just as variables are defined in JavaScript Basics 1: Syntax and Program Structure), which then becomes a function type.

const square = function (x) {
    return x * x;
};
Copy the code

This function is created using the keyword function and will take a parameter x as input. The function should also have a body in which it can return output using the keyword return, or have some side effect.

Finally, the function as a value will be assigned to the variable square, which is needed to execute/call the function, for example:

console.log(square(2));
Copy the code

Also, remember the English semicolon at the end; Suggestions must be entered and can be handed over to the code editor for auto-completion if you are afraid to forget them.

A function can have multiple arguments or no arguments at all, as follows:

Let sleep = function () {console.log(" 3 seconds passed... ") {console.log(" 3 seconds passed... ") ); }; var multiply3 = function (x, y, z) { return x * y * z; };Copy the code

The second method is slightly simpler, declaring a function by using the function keyword again, and it does not require a semicolon at the end of the function; :

function square(x) {
    return x * x;
}
Copy the code

This method allows the call to be called first (the first method above does not), and then defines it as follows:

console.log(square(2));
function square(x) {
    return x * x;
}
Copy the code

Here, you place the function declarations after the statements that call them, and the code is still valid. This allows all functions to be grouped together or in a single file while the code is organized, which is maintenance-friendly.

If the function has only one argument, you can omit the parentheses around the argument list (though this is not recommended for code consistency). If there is only one statement in the function body, the braces and return keyword can also be omitted.

const square = (x) => x * x;
Copy the code

Declaration and scope

Before delving further into the subject of functions, let’s review the first approach to function definition. You may have noticed that functions are defined in the example using the different keywords let, const, and var. What is the difference? I won’t go into detail in this article, but if you’re interested, see the Differences between Var, let, and const declarations in javascript.

In general, let and const are literal. Const stands for constant, meaning that once a const binding is declared, its value cannot be changed (although arrays and objects are different). Let bindings can be changed later.

Optional parameters

JavaScript is very loose about the number of arguments passed to functions; for example, there is the square() function defined earlier, which should theoretically take only one argument. But actually, look at the following code:

function square(x) {
    return x * x;
}
console.log(square(2, true, "test"));
Copy the code

There are no errors or exceptions when passing in extra arguments on a call. The extra arguments are ignored and the square of the first argument is computed. If too few arguments are passed, those missing arguments are assigned undefined instead of errors.

The downside of this, of course, is that it’s easy to make mistakes. So, even if it works procedurally, it should not be relied upon, which may have some unexpected consequences for the program. Therefore, it is advisable to write code in a strict manner, which can now be checked or done automatically with tools.

REST parameters

But what if you don’t know how many parameters you need? For example, you need to design a function to find the largest number in a series of numbers, but you don’t know how many numbers there are in the series, so you need to design a function that takes any number of arguments. There are two ways to do this: a REST parameter and a Arguments object.

The REST argument is simply typed with three dots in front of the argument, as follows:

function max(... numbers) { let result = -Infinity; for (const number of numbers) { if (number > result) { result = number; } } return result; } const result = max(1, 2, 3, 4, 5, 6, 7); console.log(result); / / 7Copy the code

Console. log(typeof numbers) is executed in the function, and the output is object. The REST parameter applies to the arrow function in ES6.

With arguments objects, there is no need to define variables during function definition, as follows:

function max() { let result = -Infinity; const numbers = [...arguments]; for (const number of numbers) { if (number > result) { result = number; } } return result; } const result = max(1, 2, 3, 4, 5, 6, 7); console.log(result); / / 7Copy the code

Console. log(typeof arguments) is called in the function, and the output is also object. The arguments object is a local variable available in all functions, and you can use the arguments object to refer to a function’s arguments in a function. This object contains entries for each argument passed to the function, which will help you understand the number of arguments and access them using the Arguments object.

Object Arguments do not apply to arrow functions in ES6.