1. Parameter Validation

When writing functions, it's essential to validate parameters to handle errors gracefully. This prevents unexpected behavior and makes your code more robust. For example, let's validate parameters in a function that calculates the mean score of students.

function getMeanScore(scores) {
    // Check if the input is an array
    if (!(scores instanceof Array)) {
        return NaN; // Return NaN if the input is not an array
    }

    // Calculate the sum of scores
    let sum = 0;
    for (let i = 0; i < scores.length; i++) {
        sum += scores[i];
    }

    // Return the average score
    return sum / scores.length;
}

// Test cases
console.log(getMeanScore(85));       // -> NaN
console.log(getMeanScore([80, 90])); // -> 85

2. Recursion

Recursion is a method of solving problems where a function calls itself. It's often used for tasks that can be divided into similar sub-tasks. A classic example is calculating the factorial of a number.

Iterative Factorial

The factorial function calculates the factorial of a given number n using an iterative approach.

  • Initialization: Starts with result set to 1.
  • Loop: Multiplies result by n and decrements n until n is greater than 1.
  • Return: Returns the final result.
function factorial(n) {
    let result = 1;
    while (n > 1) {
        result *= n;
        n--;
    }
    return result;
}
console.log(factorial(6)); // -> 720

Recursive Factorial

The following code recursively calculates the factorial of 6 by multiplying all integers from 6 down to 1, resulting in 720.

  • Initialization: The result variable is initially set to 1.
  • Recursive Calculation: The function calls itself with n - 1 until n is less than or equal to 1. Each call multiplies the current value of n by the result of the factorial of n - 1.
  • Return: When n becomes less than or equal to 1, it returns the final calculated result.
function factorial(n) {
    return n > 1 ? n * factorial(n - 1) : 1;
}
console.log(factorial(6)); // -> 720

3. Functions as First-Class Members

In JavaScript, functions are first-class members, meaning they can be assigned to variables, passed as arguments, and returned from other functions.

function showMessage(message) {
    console.log(`Message: ${message}`);
}
let sm = showMessage;
sm("This works!"); // -> Message: This works!
console.log(typeof sm); // -> function

4. Function Expressions

Function expressions allow you to create functions and assign them to variables. This can be done with or without naming the function.

Named Function Expression

let myAdd = function add(a, b) {
    return a + b;
}
console.log(myAdd(10, 20)); // -> 30

Anonymous Function Expression

let myAdd = function(a, b) {
    return a + b;
}
console.log(myAdd(10, 20)); // -> 30

5. Callbacks

A callback is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Synchronous Callbacks

let inner = function() {
    console.log('inner 1');
}
let outer = function(callback) {
    console.log('outer 1');
    callback();
    console.log('outer 2');
}
console.log('test 1');
outer(inner);
console.log('test 2');

Asynchronous Callbacks

let inner = function() {
    console.log('inner 1');
}
let outer = function(callback) {
    console.log('outer 1');
    setTimeout(callback, 1000); // Delayed by 1 second
    console.log('outer 2');
}
console.log('test 1');
outer(inner);
console.log('test 2');

6. setTimeout and setInterval Functions

These functions are used to execute code after a delay (setTimeout) or at regular intervals (setInterval).

Example with setInterval and setTimeout:

let inner = function() {
    console.log('inner 1');
}
let outer = function(callback) {
    console.log('outer 1');
    let timerId = setInterval(callback, 1000); // Every 1 second
    console.log('outer 2');
    setTimeout(function() {
        clearInterval(timerId); // Stop after 5.5 seconds
    }, 5500);
}
console.log('test 1');
outer(inner);
console.log('test 2');

7. Arrow Functions

Arrow functions provide a shorter syntax for writing functions. They are especially useful for inline functions.

Basic Arrow Function

let add = (a, b) => a + b;
console.log(add(10, 20)); // -> 30

Arrow Function in Recursive Case

let factorial = n => n > 1 ? n * factorial(n - 1) : 1;
console.log(factorial(5)); // -> 120

Arrow Function with forEach

let names = ['Alice', 'Eve', 'John'];
names.forEach(name => console.log(name)); // -> Alice, Eve, John

End Of Article

End Of Article