⚡ JavaScript

Funktionen und Rekursion in JavaScript (Node.js): Eine ausführliche Anleitung

Here is the translated HTML article in English. ```html

Functions and Recursion in JavaScript

Introduction: Why Do We Need Functions?

Imagine you are building a house. You don't hammer each nail by inventing a new method. You take a hammer and use it over and over. In programming, functions are like these "hammers." They are ready-made blocks of code that can be called (used) many times so you don't have to write the same thing repeatedly.

Functions make code:

  • Shorter: no need to repeat the same actions.
  • Clearer: the function name tells what it does (e.g., sumIncomes).
  • More convenient: if something needs fixing, you only change it inside the function.

Basic Syntax: How to Create and Call a Function

In JavaScript, a function is created like this:

function functionName(parameters) {
  // Function body — what it does
  return result; // (optional)
}

For the function to work, you need to call it:

functionName(arguments);

Parameters are variables the function takes as input (like empty boxes). Arguments are the specific values you put into these boxes when calling.

Example 1: Family Budget (Sum of Two Numbers)

Let's write a function that adds two incomes and returns the total amount.

// Create the function
function sumIncomes(income1, income2) {
  let totalSum = income1 + income2;
  return totalSum; // Return the result
}

// Call the function and output the result
const salary = 50000;
const freelance = 15000;
let budget = sumIncomes(salary, freelance);
console.log("Total family income:", budget); // Output: 65000

How it works: The function sumIncomes takes two numbers, adds them, and returns the sum. We save the result in the variable budget and output it.

Example 2: Temperature Comparison (Return the Maximum Number)

The function takes two temperatures and returns the higher one.

function findMax(temp1, temp2) {
  if (temp1 > temp2) {
    return temp1;
  } else {
    return temp2;
  }
}

let morning = 15;
let afternoon = 22;
let highest = findMax(morning, afternoon);
console.log("Highest temperature:", highest); // Output: 22

Example 3: Checking if a Number is Even

Let's check if the number of boxes is even. The function returns true (yes) or false (no).

function isEven(number) {
  if (number % 2 === 0) {
    return true;
  } else {
    return false;
  }
}

let boxes = 150;
console.log("Is the quantity even?", isEven(boxes)); // Output: true

Recursion: A Function Calling Itself

Recursion is when a function calls itself to solve a big problem by breaking it down into small identical steps. It's like a Russian nesting doll: inside the big doll, there is a smaller one, and so on.

Important rule: Recursion must always have a base case — a condition that stops the function; otherwise, it will call itself infinitely and the program will "freeze."

Example 4: Reversing a String with Recursion

Let's break down the task: we need to reverse a string. For example, "cat" → "tac".

function reverse(str) {
  // Base case: if the string is empty or has one character, return it
  if (str.length <= 1) {
    return str;
  }
  // Recursion: take the last character + reverse the remaining part
  return str[str.length - 1] + reverse(str.slice(0, -1));
}

let message = "hello";
console.log("Reversed string:", reverse(message)); // Output: olleh

How it works:

  1. The function takes the last character (o) and calls itself for the string without the last character (hell).
  2. The new call takes l and calls itself for hel.
  3. This continues until the string becomes empty.
  4. All characters are collected in reverse order.

Example 5: Finding the Minimum Element in a List (Recursion)

Let's find the lowest temperature of the day. We have an array of numbers.

function findMin(arr) {
  // Base case: if the array has one element, it is the minimum
  if (arr.length === 1) {
    return arr[0];
  }
  // Find the minimum in the tail of the array (without the first element)
  let minOfRest = findMin(arr.slice(1));
  // Compare the first element with the minimum of the rest
  if (arr[0] < minOfRest) {
    return arr[0];
  } else {
    return minOfRest;
  }
}

let temperatures = [15, 8, 22, 3, 10];
console.log("Minimum temperature:", findMin(temperatures)); // Output: 3

Common Beginner Mistakes

  • Forgetting to call the function. If you just write sumIncomes (without parentheses), the program won't execute the code inside. Always use parentheses: sumIncomes(50000, 15000).
  • Forgetting return. If you don't write return, the function will return undefined (empty). A function without return does something but doesn't give the result back.
  • Infinite recursion. If you don't write a base case, the function will call itself forever until memory runs out. Always check the stopping condition!
  • Confusing parameters and arguments. Parameters are the "variables" in the function definition. Arguments are the "values" you pass when calling.

Final Example: Solving a Similar Problem

Task: At a factory, they count boxes. We need to write a function that takes an array of numbers (the number of boxes in each batch) and returns their sum. Use recursion.

function sumBoxes(boxes) {
  // Base case: if the array is empty, the sum is 0
  if (boxes.length === 0) {
    return 0;
  }
  // Recursion: first element + sum of the rest
  return boxes[0] + sumBoxes(boxes.slice(1));
}

let batches = [10, 25, 15, 30];
console.log("Total boxes:", sumBoxes(batches)); // Output: 80
```