Functions

Functions in JavaScript

Your JavaScript files will contain a series of functions, which are actions that the computer or browser will carry out. For clarity of code, each function should have one core task. More complex functions will generally be a series of smaller functions defined externally to it. By breaking down your program into smaller, manageable functions, you can keep your code organized, reusable, and easier to debug. Proper naming conventions, documentation using docstrings, and clear function definitions will help make your code more readable and maintainable.

When naming functions in JavaScript, it's a common practice to use camelCase. This means the first word is lowercase, and each subsequent word starts with an uppercase letter without spaces between words. For example: exampleCamelCaseFunctionName.

Docstrings

A docstring is a special type of comment that can be placed above functions (or other code structures) to describe their purpose, parameters, and return values. It is a valuable tool for documenting your code, especially when working in large projects or teams. Docstrings are typically multi-line comments and can even be used by documentation generators to create an automatic reference for your code. It starts with /**, has each line starting with * and ends with */. Later when you hover over a function you have created, it will display the docstring.

/**
* This is a docstring.
* It describes the purpose of the function and how it works.
* List the parameters with the following syntax, specifying the data type
* @param {number} param1 - The first parameter.
* @param {number} param2 - The second parameter.
* @returns {number} The result of adding both parameters.
*/
function add(param1, param2) {
    return param1 + param2;
}

Defining a Function

A function can be defined using the function keyword followed by the function name and a set of parameters in parentheses and then curly brackets to house the code block for the function. Here's the basic structure of a function.

function functionName(param1, param2) {
    // Code to execute
}

You can assign default values to function parameters using an = sign. If an argument is not passed when calling the function, the default value is used instead.

function greet(name = 'Guest') {
    console.log('Hello, ' + name);
}
greet(); // Outputs: Hello, Guest
greet('Adam'); // Outputs: Hello, Adam

You can assign a function to a variable and give it a new name. This is commonly done with anonymous functions (functions without a name):

functionOne(a, b) {
    return a + b;
};
const addNumbers = functionOne;
addNumbers(1, 2); // returns 3

Now, you can call the function using the addNumbers variable. Note that in the line where you reassign the function name, you do not need the parenthesis on the function.

Arguments and Parameters

Parameters are variables that are listed inside the parentheses when you define the function. They act as placeholders for the values the function will use.

Arguments are the actual values you pass when calling the function.

function sum(a, b) {
    console.log(a + b);
}

sum(2, 3); // Arguments: 2, 3; Parameters: a, b

If a function is called with more arguments than defined parameters, the extra arguments are ignored. Conversely, if fewer arguments are provided, the missing parameters will be set to undefined by default.

You can check the number of arguments passed to a function using the arguments.length property, which returns the number of arguments passed, regardless of how many parameters were defined.

function logArguments() {
    console.log(arguments.length); // Logs the number of arguments passed
}

logArguments(1, 2, 3); // Outputs: 3

Return

Functions in JavaScript can return values, which can then be used later in your program. This is useful when you need to store the result of a function for further processing or display. If no return statement is specified, the function will return undefined.

function multiply(x, y) {
    return x * y;
}
let result = multiply(4, 5); // Returns the output of the function and assigns it to this variable
console.log(result); // Outputs: 20

Helper Functions

You can define helper functions inside other functions. These "inner" functions are useful for encapsulating smaller tasks that are only needed within the parent function.

outerFunction(x, y) {
    function innerFunction(a, b) {
        return a + b;
    }

    return innerFunction(x, y);
}

console.log(outerFunction(2, 3)); // Outputs: 5

Arrow Functions

Arrow functions are a shorthand way of writing functions introduced in ES6. They remove the need to type the function keyword and often make your code cleaner and more concise.

const functionName = (param1, param2) => {
    // function body
    return result;
};

0, 1, and >1 parameter arrow functions have different requirements for parentheses around the parameters.

const functionName = () => {}; // Parentheses needed for 0 parameters
const functionName = param1 => {}; //No parenthesis needed for 1 parameter
const functionName = (param1, param2) => {}; // Comma separated list inside parentheses for more than 1 parameter

Arrow functions automatically return the value of a single expression without needing the return keyword or curly braces.

const doubleFunction = x => x * 2;
const greet = name => `Hello, ${name}`;

Arrays and Functions

If you pass an array as an argument into a function, changes made within this function will affect the original array.

function addFruit(arr) {
    arr.push('jackfruit');
}
addFruit(fruits);
console.log(fruits); // 'jackfruit' is added to the fruits array